How to compare in shell script?
How to compare in shell script?
Or, why the following scr开发者_Go百科ipt prints nothing?
x=1
if[ $x = 1 ] then echo "ok" else echo "no" fi
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 =.
Short solution with shortcut AND and OR:
x=1
(( $x == 1 )) && echo "ok" || echo "no"
You could compare in shell in two methods
- Single-bracket syntax (
if [ ]) - Double-parenthesis syntax (
if (( )))
Using Single-bracket syntax
Operators :-
-eqis equal to
-neis not equal to
-gtis greater than
-geis greater than or equal to
-ltis less than
-leis 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
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.
加载中,请稍侯......
精彩评论