Quiz Entry - updated: 2026.06.20
How do you use elif for multiple conditions in Bash?
elif ("else if") chains extra conditions — bash tests each in order and runs only the first block whose condition is true, skipping the rest.
elif keeps multi-way decisions flat and readable instead of nesting if inside else. The key behaviour is short-circuiting: once one branch matches, none of the later conditions are even evaluated, and the optional final else is the catch-all when nothing matched. Order your conditions from most-specific to most-general.
if [ CONDITION1 ]; then
# runs if CONDITION1 is true
elif [ CONDITION2 ]; then
# runs only if CONDITION1 was false AND CONDITION2 is true
else
# runs if none matched
fi
Example - choose database client:
#!/bin/bash
systemctl is-active mariadb > /dev/null 2>&1
MARIADB=$?
systemctl is-active postgresql > /dev/null 2>&1
POSTGRES=$?
if [ "$MARIADB" -eq 0 ]; then
mysql
elif [ "$POSTGRES" -eq 0 ]; then
psql
else
sqlite3
fi
Tip: You can chain as many elif blocks as needed. Only the first matching condition executes.