LinuxCommandLibrary
GitHubF-DroidGoogle Play Store

elif

Conditional else-if construct in shell scripts

TLDR

Use elif in bash script
$ if [condition1]; then echo "first"; elif [condition2]; then echo "second"; fi
copy
Multiple elif conditions
$ if [ $x -lt 0 ]; then echo "negative"; elif [ $x -eq 0 ]; then echo "zero"; elif [ $x -gt 0 ]; then echo "positive"; fi
copy
Branch on a command's exit status rather than a test
$ if command -v nvim; then echo "nvim"; elif command -v vim; then echo "vim"; else echo "none"; fi
copy

SYNOPSIS

if condition; then commands; elif condition; then commands; fi

DESCRIPTION

elif is a shell keyword used in bash and other POSIX shells for conditional branching. It's short for "else if" and allows multiple conditions to be tested sequentially.elif follows an if statement and precedes then. Multiple elif blocks can appear before an optional else. Only the first matching condition's block executes.This construct is fundamental to shell scripting for implementing multi-way branching logic.

CAVEATS

elif is a shell reserved word, not a program, so `which elif` finds nothing and it cannot be used outside an if block. Each elif needs its own then, and the whole chain still ends with a single fi. Inside `[ ... ]` every token must be separated by spaces: `[$x -eq 1]` is a syntax error. The condition is a command list, so it branches on the exit status, and any command works there, not just test.

HISTORY

elif is part of POSIX shell syntax, inherited from the Bourne shell created by Stephen Bourne at Bell Labs in the 1970s. It provides cleaner syntax than nested if-else blocks.

SEE ALSO

if(1), else(1), fi(1), test(1), bash(1)

Braincup
Open source brain training for math, memory and focus
Braincup mini-games
41 mini-games · Apache-2.0
No ads · No tracking
Play in browser
Download Braincup on the App StoreGet Braincup on Google PlayGet Braincup on F-Droid
276 stars
From the maker of Linux Command Library
Copied to clipboard
Braincup
Open source brain training for math, memory and focus. 41 mini-games, from mental arithmetic to Sudoku, N-Back and Solo Chess.
Apache-2.0 licensed · No ads · No tracking · No account
From the maker of Linux Command Library
Download Braincup on the App StoreGet Braincup on Google PlayGet Braincup on F-Droid