Vijay
Vijay

Reputation: 67291

Comparing strings for equality in 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.

Upvotes: 7

Views: 76802

Answers (5)

Aaron Digulla
Aaron Digulla

Reputation: 328724

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).

Upvotes: 5

soulmerge
soulmerge

Reputation: 75724

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.

Upvotes: 0

Andre Miller
Andre Miller

Reputation: 15513

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

Upvotes: 18

Alberto Zaccagni
Alberto Zaccagni

Reputation: 31580

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.

Upvotes: 7

ghostdog74
ghostdog74

Reputation: 342609

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

Upvotes: 2

Related Questions