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 :-
-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
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.
精彩评论