Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 785
The Student Avatar asked Mar 17 '11 18:03

The Student


3 Answers

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

like image 74
William Durand Avatar answered Oct 09 '22 22:10

William Durand


Short solution with shortcut AND and OR:

x=1
(( $x == 1 )) && echo "ok" || echo "no"
like image 5
user unknown Avatar answered Oct 09 '22 20:10

user unknown


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
like image 2
anoopknr Avatar answered Oct 09 '22 21:10

anoopknr