LinuxCommandLibrary

elif

Chain conditional statements in scripts

TLDR

View documentation for if command

$ tldr if
copy

SYNOPSIS

if test-command; then commands; [elif test-command; then commands;]... [else commands;] fi

DESCRIPTION

elif is a reserved keyword in Unix-like shells such as Bash, Dash, and Zsh, used within if statements for multi-condition branching. It provides an 'else if' construct, allowing sequential evaluation of conditions until one succeeds.

After an initial if block, one or more elif clauses can follow, each with its own test condition. The shell executes the commands in the first true block and skips the rest, including any trailing else. The structure must end with fi.

Conditions are command lists; success (exit status 0) triggers the block. This enables readable, nested logic without deep if-else chains.

Example flow:
- Test condition 1 → true? Run commands1.
- Else, test condition 2 → true? Run commands2.
- Continue until else or end.

elif enhances script control flow, common in automation, configuration, and decision scripts. It is POSIX-standard, ensuring portability across shells.

CAVEATS

elif is not standalone; must follow if in same compound statement. Indentation optional but vital for readability. Infinite elif chains possible but risk stack overflow.

BASIC EXAMPLE

if [ "$#" -eq 0 ]; then
  echo "No args"
elif [ "$1" = "help" ]; then
  echo "Usage: script arg"
else
  echo "Arg: $1"
fi

COMPOUND CONDITIONS

Supports complex tests: elif [[ $var -gt 10 && $var -lt 20 ]]; then ... Use test, [, or [[ for evaluations.

HISTORY

Introduced in Bill Joy's C-shell (csh, 1978) and adopted in Bourne shell derivatives like ksh (1983). POSIX.1-1992 standardized it for portable shell scripting.

SEE ALSO

bash(1), dash(1), test(1), [(1), case(1)

Copied to clipboard