What is the difference between "elif" and "else if" in shell scripting?
I try an answer in one sentence: If you use elif
you deal with one if-clause, if you use else if
with two if-clauses.
Look at these simple examples:
testone() {
if [[ $CASE == 1 ]]; then
echo Case 1.
elif [[ $CASE == 2 ]]; then
echo Case 2.
else
echo Unknown case.
fi
}
This is formally (tidy indention makes sense sometimes) one if-clause as you can see that each case is at the same hierarchy level.
Now, the same function with else if
:
testtwo() {
if [[ $CASE == 1 ]]; then
echo Case 1.
else
if [[ $CASE == 2 ]]; then
echo Case 2.
else
echo Unknown case.
fi
fi
}
You have formally two cascaded if-clauses and accordingly two closing fi
statements. Plaese note that it makes no difference here if I write else if
in one line (as in your question) or in two lines (as in my example).
My guess why both forms are used in the same script: If you already have a complete if-clause written, but need (logic reasons) to copy/cut & paste that into an existing if-clause, you end up with else if
. But when you write the complete if-clause from scratch you probably use the IMHO simpler-to-read form elif
.
Related videos on Youtube
Zeena Pinto
Updated on September 18, 2022Comments
-
Zeena Pinto over 1 year
I am very new to shell scripting.
When I look at some code, written for ksh (
#!/bin/ksh
) I see there iselse if
as well aselif
used in one script.So, what is the difference between
else if
andelif
in shell scripting?-
Paul over 9 yearsWhat does the first line of the script say? Something like
#!/bin/bash
-
Zeena Pinto over 9 yearsIt says #!/bin/ksh
-
ghoti over 9 yearsPlease specify the shell in your question and with a tag. There are many shells, and they all have slightly (or radically) different syntax.
-
Paul over 9 yearsI think you will want to edit and add sample code. ksh supports
if
,else
, andelif
, butelse if
is unusual. -
Henk Langeveld over 9 yearsNesting.
else if
starts another level and more complexity. You want to avoid complexity.
-