开发者

Comparing strings for equality in ksh

开发者 https://www.devze.com 2022-12-10 11:40 出处:网络
i am testing with the shell script below: #!/bin/ksh -x instance=`echo $1 | cut -d= -f2` if [ $instance == \"ALL\" ]

i am testing with the shell script below:

#!/bin/ksh -x


instance=`echo $1 | cut -d= -f2`
if [ $instance == "ALL" ]
then
echo "strings matched \n"
fi

It's giving this error in the if condition:

: ==: unknown test operator

is == really not the correct syntax to use? I am running on the command line as below

test_lsn_2 INST开发者_Python百科ANCE=ALL

Could anybody please suggest a solution. Thanks.


To compare strings you need a single =, not a double. And you should put it in double quotes in case the string is empty:

if [ "$instance" = "ALL" ]
then
    echo "strings matched \n"
fi


I see that you are using ksh, but you added bash as a tag, do you accept a bash-related answer? Using bash you can do it in these ways:

if [[ "$instance" == "ALL" ]]
if [ "$instance" = "ALL" ]
if [[ "$instance" -eq "ALL" ]]

See here for more on that.


Try

if [ "$instance" = "ALL" ]; then

There were several mistakes:

  1. You need double quotes around the variable to protect against the (unlikely) case that it's empty. In this case, the shell would see if [ = "ALL" ]; then which isn't valid.

  2. Equals in the shell uses a single = (there is no way to assign a value in an if in the shell).


totest=$1
case "$totest" in
  "ALL" ) echo "ok" ;;
  * ) echo "not ok" ;;
esac


I'va already answered a similar question. Basically the operator you need is = (not ==) and the syntax breaks if your variable is empty (i.e. it becomes if [ = ALL]). Have a look at the other answer for details.

0

精彩评论

暂无评论...
验证码 换一张
取 消