“if” statement won't work on Debian Linux

微笑、不失礼 提交于 2019-12-13 14:43:27

问题


I have a bash script which contains the following "if" statement. The problem is I can't get it to run on Debian (it runs fine on Fedora and CentOS).

if [ $1 == "--daily" ]  # <--- line 116
then
countDaily
elif [ $1 == "--monthly" ] # <--- line 119
then
countMonthly
fi

after running it:

sh /home/kris/countsc.sh --daily

I'm getting an error:

/home/kris/countsc.sh: 116: [: --daily: unexpected operator
/home/kris/countsc.sh: 119: [: --daily: unexpected operator

回答1:


Since you are using sh, and not bash, you should use a single equal = to do the string comparison, instead of the double equal ==. Also it is a good practice to double quote the variable in test statement (this error is not caused by incorrect quoting though).

The comparison should be:

if [ "$1" = "--daily" ]

and

elif [ "$1" = "--monthly" ]



回答2:


As far as I'm aware, there is no double-equal operator in test, which is used in this case. If you want to test for string equality, just use a single equals sign, like this :

if [ $1 = "--daily" ]
elif [ $1 = "--monthly" ]

You should also remember to wrap $1 into quotes in case it contains spaces.

You might also want to consider using the "new test" instruction in Bash, e.g. [[ and corresponding ]], which has many advantages over [, which is a leftover from the days of sh. Check out this document in order to find out about the advantages.



来源:https://stackoverflow.com/questions/18828196/if-statement-wont-work-on-debian-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!