Student
Student

Reputation: 28345

How to compare in shell script?

How to compare in shell script?

Or, why the following script prints nothing?

x=1
if[ $x = 1 ] then echo "ok" else echo "no" fi

Upvotes: 8

Views: 52922

Answers (4)

anoopknr
anoopknr

Reputation: 3355

You could compare in shell in two methods

  1. Single-bracket syntax ( if [ ] )
  2. Double-parenthesis syntax ( if (( )))

Using Single-bracket syntax

Operators :-

-eq is equal to

-ne is not equal to

-gt is greater than

-ge is greater than or equal to

-lt is less than

-le is less than or equal to

In Your case :-

x=1
if [ $x -eq 1 ]
then 
  echo "ok" 
else 
  echo "no" 
fi

Double-parenthesis syntax

Double-parentheses construct is also a mechanism for allowing C-style manipulation of variables in Bash, for example, (( var++ )).

In your case :-

x=1
if (( $x == 1 )) # C like statements 
then
    echo "ok"
else
    echo "no"
fi

Upvotes: 3

user unknown
user unknown

Reputation: 36229

Short solution with shortcut AND and OR:

x=1
(( $x == 1 )) && echo "ok" || echo "no"

Upvotes: 6

Aif
Aif

Reputation: 11220

It depends on the language. With bash, you can use == operator. Otherwize you may use -eq -lt -gt for equals, lowerthan, greaterthan.

$ x=1
$ if [ "$x" == "2" ]; then echo "yes"; else echo "no"; fi
no

Edit: added spaces arround == and tested with 2.

Upvotes: 1

William Durand
William Durand

Reputation: 5519

With numbers, use -eq, -ne, ... for equals, not equals, ...

x=1
if [ $x -eq 1 ]
then 
  echo "ok" 
else 
  echo "no" 
fi

And for others, use == not =.

Upvotes: 12

Related Questions