What is the difference between "elif" and "else if" in shell scripting?

27,837

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.

Share:
27,837

Related videos on Youtube

Zeena Pinto
Author by

Zeena Pinto

Updated on September 18, 2022

Comments

  • Zeena Pinto
    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 is else if as well as elif used in one script.

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

    • Paul
      Paul over 9 years
      What does the first line of the script say? Something like #!/bin/bash
    • Zeena Pinto
      Zeena Pinto over 9 years
      It says #!/bin/ksh
    • ghoti
      ghoti over 9 years
      Please specify the shell in your question and with a tag. There are many shells, and they all have slightly (or radically) different syntax.
    • Paul
      Paul over 9 years
      I think you will want to edit and add sample code. ksh supports if, else, and elif, but else if is unusual.
    • Henk Langeveld
      Henk Langeveld over 9 years
      Nesting. else if starts another level and more complexity. You want to avoid complexity.