Skip to content
Joachim Ansorg edited this page Nov 12, 2021 · 3 revisions

Use elif instead of else if.

Problematic code:

if [ "$#" -eq 0 ]
then
  echo "Usage: ..."
else if [ "$#" -lt 2 ]
then
  echo "Missing operand"
fi
  

Correct code:

if [ "$#" -eq 0 ]
then
  echo "Usage: ..."
elif [ "$#" -lt 2 ]
then
  echo "Missing operand"
fi

Rationale:

Many languages allow alternate branches with else if, but sh is not one of them. Use elif instead.

Exceptions:

else if is a valid (though confusing) way of nesting an if statement in a parent's else. If this is your intention, consider using canonical formatting by putting a linefeed between else and if.

This does not change the behavior of the script, but merely makes it more obvious to ShellCheck (and other humans) that you didn't expect the else if to behave the way it does in C. Alternatively, you can ignore it with no ill effects.

if x
then
  echo "x"
else     # line break here
  if y
  then
    echo "y"
   fi 
fi

ShellCheck

Each individual ShellCheck warning has its own wiki page like SC1000. Use GitHub Wiki's "Pages" feature above to find a specific one, or see Checks.

Clone this wiki locally