Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using if elif fi in shell scripts [duplicate]

Tags:

bash

shell

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

like image 895
Zenet Avatar asked Mar 01 '10 21:03

Zenet


People also ask

What is difference between if-else Fi and if Elif else Fi statement?

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.

What is Elif in shell script?

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.

Can you have multiple Elif in bash?

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.


3 Answers

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 
like image 198
Splitlocked Avatar answered Oct 10 '22 11:10

Splitlocked


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.

like image 25
Josh Lee Avatar answered Oct 10 '22 11:10

Josh Lee


Use double brackets...

if [[ expression ]]

like image 29
Henryk Konsek Avatar answered Oct 10 '22 09:10

Henryk Konsek