4

I am very new to shell scripting.

When I look at some code, written for ksh (#!/bin/ksh) I see there is else if as well as elif used in one script.

So, what is the difference between else if and elif in shell scripting?

  • 2
    What does the first line of the script say? Something like #!/bin/bash – Paul Oct 17 '14 at 21:18
  • It says #!/bin/ksh – Zeena Pinto Oct 17 '14 at 21:27
  • Please specify the shell in your question and with a tag. There are many shells, and they all have slightly (or radically) different syntax. – ghoti Oct 17 '14 at 22:26
  • 1
    I think you will want to edit and add sample code. ksh supports if, else, and elif, but else if is unusual. – Paul Oct 18 '14 at 1:48
  • Nesting. else if starts another level and more complexity. You want to avoid complexity. – Henk Langeveld Oct 20 '14 at 7:57
5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.