3

我有一个 bash 脚本,其中包含以下“if”语句。问题是我无法让它在 Debian 上运行(它在 Fedora 和 CentOS 上运行良好)。

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

运行后:

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

我收到一个错误:

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

2 回答 2

5

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" ]
于 2013-09-16T12:39:26.787 回答
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.

于 2013-09-16T12:39:15.617 回答