脚本执行,出现如下错误:“h.sh: line 9: [: ==: unary operator expected”,具体脚本如下:
[root@Dasoncheng sbin]# cat -n h.sh 1 #!/bin/bash 2 sh -n $1 &>/tmp/err 3 if [ $? -eq 0 ]; 4 then 5 echo "The script is ok" 6 else 7 cat /tmp/err 8 read -p "Please input q/Q to exit , or others to edit it by vim: " n 9 if [ $n == "q" ] || [ $n == "Q" ]; 10 then 11 exit 12 else 13 vim $1 14 exit 15 fi 16 fi[root@Dasoncheng sbin]# sh h.sh i.sh i.sh: line 3: syntax error: unexpected end of filePlease input q/Q to exit , or others to edit it by vim: h.sh: line 9: [: ==: unary operator expectedh.sh: line 9: [: ==: unary operator expected ##这个就是执行的报错信息;
解决办法:
if [ $n == "q" ] || [ $n == "Q" ];修改为:if [ "$n" == "q" ] || [ "$n" == "Q" ];##即可;
因为当$n为空值时(即回车 未输入任何参数),那么就成了 [ = "q"]了,显然缺少了对比参数。当$n值不为空时,脚本还是正常的;
使用如下几种方法,也可以避免:if [[ $n == "q" ]] || [[ $n == "Q" ]]##或者if [ "$n"x == "q"x ] ##其中x也可以为其他字符;