“if” statement won't work on Debian Linux

2019-07-05 23:34发布

问题:

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.



标签: linux sh