I'm not sure how to do an if
with multiple tests in shell. I'm having trouble writing this script:
echo "You have provided the following arguments $arg1 $arg2 $arg3"
if [ "$arg1" = "$arg2" && "$arg1" != "$arg3" ]
then
echo "Two of the provided args are equal."
exit 3
elif [ $arg1 = $arg2 && $arg1 = $arg3 ]
then
echo "All of the specified args are equal"
exit 0
else
echo "All of the specified args are different"
exit 4
fi
The problem is I get this error every time:
./compare.sh: [: missing `]' command not found
In several other languages, the elif is written as “elseif” or “else if”. The elif statement helps us to make decisions among different choices. The “if' keyword is followed by the condition you want to check. In this if-else-if conditional statement, the expressions are evaluated from top to bottom.
To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part.
In Bash elif, there can be several elif blocks with a boolean expression for each one of them. In the case of the first 'if statement', if a condition goes false, then the second 'if condition' is checked.
Josh Lee's answer works, but you can use the "&&" operator for better readability like this:
echo "You have provided the following arguments $arg1 $arg2 $arg3" if [ "$arg1" = "$arg2" ] && [ "$arg1" != "$arg3" ] then echo "Two of the provided args are equal." exit 3 elif [ $arg1 = $arg2 ] && [ $arg1 = $arg3 ] then echo "All of the specified args are equal" exit 0 else echo "All of the specified args are different" exit 4 fi
sh
is interpreting the &&
as a shell operator. Change it to -a
, that’s [
’s conjunction operator:
[ "$arg1" = "$arg2" -a "$arg1" != "$arg3" ]
Also, you should always quote the variables, because [
gets confused when you leave off arguments.
Use double brackets...
if [[ expression ]]
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