The difference between “elif” and “else if” in shell scripting

kshshellunix

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?

Best Answer

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.