bash 脚本格式引起的错误

abloz 2009-03-23
2009-03-23

周海汉/文

bash脚本其实是格式脚本,并不像C语言那样自由。

比如,对于赋值


  1. [zhouhh@cvttdev ~]$ r=ls -l test
  2. [zhouhh@cvttdev ~]$ echo $r
  3. -rwxrwxr-x 1 zhouhh zhouhh 176 03-16 16:35 test
  4. [zhouhh@cvttdev ~]$ ret =ls -l test
  5. -bash: ret: command not found
  6. [zhouhh@cvttdev ~]$ ret= ls -l test
  7. -bash: -rwxrwxr-x: command not found

[zhouhh@cvttdev ~]$ r=ls -l test [zhouhh@cvttdev ~]$ echo $r -rwxrwxr-x 1 zhouhh zhouhh 176 03-16 16:35 test [zhouhh@cvttdev ~]$ ret =ls -l test -bash: ret: command not found [zhouhh@cvttdev ~]$ ret= ls -l test -bash: -rwxrwxr-x: command not found

对于C语言,赋值号左右都可以有空格,而在bash脚本中,因为有空格,导致了错误。如果左边有空格,会将变量当成命令执行。如果右边有空格,会将变量赋值为空格。

这容易引起的误会是不知道如何在bash中给变量赋值。其实只要将空格去掉就行了。

又如,对于if语句


  1. #!/bin/bash
    1. a=”234”
  2. if[ $a==”234”]; then
  3. echo “ok”
  4. fi
      1. [zhouhh@cvttdev ~]$ ./test1
  5. ./test1: line 4: syntax error near unexpected token `then’
  6. ./test1: line 4: `if[ $a==”234”]; then’

#!/bin/bash a=”234” if[ $a==”234”]; then echo “ok” fi [zhouhh@cvttdev ~]$ ./test1 ./test1: line 4: syntax error near unexpected token then' ./test1: line 4: if[ $a==”234”]; then’

因为if后面没有空格


如非注明转载, 均为原创. 本站遵循知识共享CC协议,转载请注明来源