Bash 脚本错误[ : ! = : 一元运算符预期

在我的脚本中,我试图检查第一个和唯一的参数是否等于 -v,但它是一个可选的参数。我使用了 如果语句,但是一元操作符总是出现预期错误。

这是密码:

if [ $1 != -v ]; then
echo "usage: $0 [-v]"
exit
fi

更具体地说:

上面的脚本的这一部分是检查一个可选参数,然后,如果没有输入参数,它应该运行程序的其余部分。

#!/bin/bash


if [ "$#" -gt "1" ]; then
echo "usage: $0 [-v]"
exit
fi


if [ "$1" != -v ]; then
echo "usage: $0 [-v]"
exit
fi


if [ "$1" = -v ]; then
echo "`ps -ef | grep -v '\['`"
else
echo "`ps -ef | grep '\[' | grep root`"
fi
154093 次浏览

Quotes!

if [ "$1" != -v ]; then

Otherwise, when $1 is completely empty, your test becomes:

[ != -v ]

instead of

[ "" != -v ]

...and != is not a unary operator (that is, one capable of taking only a single argument).

Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

#!/bin/sh
case $1 in
'-v') if [ "$1" = -v ]; then
echo "`ps -ef | grep -v '\['`"
else
echo "`ps -ef | grep '\[' | grep root`"
fi;;
*) echo "usage: $0 [-v]"
exit 1;; #It is good practice to throw a code, hence allowing $? check
esac

If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

#!/bin/sh


usage ()
{
echo "usage: $0 [-v]"
exit 1
}


unset arg_match


for arg in $*
do
case $arg in
'-v') if [ "$arg" = -v ]; then
echo "`ps -ef | grep -v '\['`"
else
echo "`ps -ef | grep '\[' | grep root`"
fi
arg_match=1;; # this is set, but could increment.
*) ;;
esac
done


if [ ! $arg_match ]
then
usage
fi

But, allow multiple occurrences of an argument is convenient to use in situations such as:

$ adduser -u:sam -s -f -u:bob -trace -verbose

We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

$ adduser -u sam -s -f -u bob -trace -verbose