开发者

Error with Bash script - syntax error

File: test.sh

Command: sh test.sh

Content of test.sh

   x=1
    while [ $x -le 5 ]
    do
      echo "Welcome $x times"
      x=$(( $x + 1 ))
    done

Error:

test.sh: line 6: syntax error near unexpected token `done'

t开发者_如何学编程est.sh: line 6: `done'

GNU bash, version 3.2.39(1)-release (x86_64-pc-linux-gnu)


It works when I run that code.

Make sure you're running with bash not sh. The $(( )) construct is relatively new.


Run your script with:

bash test.sh

It will work. There are two main possibilities:

  • When it is run as sh, bash does not necessarily recognize all the syntax that it recognizes when it is run as bash. On the Linux and MacOS X machines where I tested this, though, both sh and bash worked fine.
  • Alternatively, you might be on a machine running AIX, HP-UX, Solaris or similar, where /bin/sh is not the same shell as bash at all. It is more rigid Bourne shell, where the notation you used is invalid - a syntax error.


That's strange on my system I get.

Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times

Must have something to do with whitespace.


Say hello to semicolons. :)

x=1
while [ $x -le 5 ]
do
  echo "Welcome $x times";
  x=$(( $x + 1 ));
done

You don't need a semicolon if it's one line, however, you might want to do a loop this way:

for i in `seq 1 5`
do
  echo "Welcome $i times"
done
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜