Frequently Asked Question

How do if, elif, and else actually work in bash?

if in bash tests the exit status of a command, not a boolean value. The full form is if cmd; then ...; elif cmd; then ...; else ...; fi: bash runs the first cmd, and if it returns zero, runs the then branch; otherwise it tries the next elif, and so on until something succeeds or it hits else. That means the "condition" can be any command at all, if grep -q foo file; then ... is perfectly idiomatic, no brackets needed, because grep -q returns zero when it finds a match.

The brackets [ ... ] and [[ ... ]] you commonly see are just commands that return an exit code based on their arguments: [ 1 -eq 1 ] returns zero (true). The keyword fi closes the block, it is if reversed, a Bourne-shell convention. Bash also has a case ... esac construct for matching one value against many patterns, which is cleaner than a long chain of elif [[ $x == ... ]] when you are dispatching on a single variable.

Further reading and video