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
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
if [ ]
)if (( ))
)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-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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With