Bash 5 reference · Shell Builtins and Syntax

if (Bash builtin)

Run commands depending on whether a command succeeds (exit status 0), with optional elif and else branches.

Bash 5

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

if COMMANDS; then ...; elif COMMANDS; then ...; else ...; fi

Parameters

ParameterDescription
condition Any command; [[ ]], (( )) and grep -q are common.

Examples

if, elif and else
for n in 3 12; do
  if (( n > 10 )); then echo "$n is big"; elif (( n > 5 )); then echo "$n is medium"; else echo "$n is small"; fi
done

Output

3 is small
12 is big

Run this on your computer — see “Get Started” for setup.

Any command as a condition
echo 'ERROR disk full' > app.log
if grep -q ERROR app.log; then echo 'errors found'; fi

Output

errors found

Run this on your computer — see “Get Started” for setup.

Was this page helpful?