Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing strings for equality in ksh

Tags:

bash

shell

unix

ksh

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 INSTANCE=ALL

Could anybody please suggest a solution. Thanks.

like image 359
Vijay Avatar asked Nov 02 '09 10:11

Vijay


2 Answers

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
like image 70
Andre Miller Avatar answered Sep 22 '22 03:09

Andre Miller


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.

like image 42
Alberto Zaccagni Avatar answered Sep 19 '22 03:09

Alberto Zaccagni