我在ubuntu虚拟机下练习《鸟哥的Linux私房菜》中的shell脚本例子时,我习惯用vim编写完直接用sh xxx.sh来运行,

并且还可以用sh -n xxx.sh 或者-x,-v等参数来调试脚本。当运行if then语句的例子时,突然报错:xxx unexpected operator,

我暂且没有管它,因为我认为代码没有问题,并且我把if then的语句理解了就达到了学习的目的。

但是在练习用“[ ]”中括号来做判断时,还是这个问题,我决定寻求网络解决这个问题。

代码类似:

[plain] view plaincopyunexpected operator--shell script _Linuxunexpected operator--shell script _Linux_02

  1. read -p "Please input (Y/N): " yn  

  2. [ "$yn" == "Y" -o "$yn" == "y" ] && echo "OK, continue" && exit 0  

  3. [ "$yn" == "N" -o "$yn" == "n" ] && echo "Oh, interrupt!" && exit 0  

  4. echo "I don't know what your choice is" && exit 0  


[plain] view plaincopyunexpected operator--shell script _Linuxunexpected operator--shell script _Linux_02

  1. #!/bin/bash  

  2.   

  3. read -p "input yes or no(Y/N):" yesorno  

  4.   

  5. if [ "$yesorno" == "Y" ] || [ "$yesorno" == "y" ]; then  

  6.         echo "okay, you say yes."  

  7. else  

  8.         echo "oh, no."  

  9. fi  


原因应该是在ubuntu中默认的脚本语言是dash,用sh运行会采用dash的语言规则,所以会有如此错误。

如果用“./xxx.sh”来运行就没有问题了。那么咱们必须要用sh加参数来调试我们的脚本,怎么办?

好办,只需做一下配置修改就可以了。将使用dash 作为默认的系统脚本的选项取消掉。

命令为:

[plain] view plaincopyunexpected operator--shell script _Linuxunexpected operator--shell script _Linux_02

  1. sudo dpkg-reconfigure dash  


此时会跳到下面的配置页面,选择no并回车就好了。unexpected operator--shell script _ubuntu_07