Learn/Bash/4. Conditionals and tests
Lesson 4 of 8
Sign in

Bash, lesson 4

Conditionals and tests

In most languages, if checks whether an expression is true. In Bash, if runs a command and checks its exit status: 0 (success) takes the then branch, anything else does not. Bash gives you special commands whose only job is to test things.

The block ends with fi ("if" backwards). The ; before then separates the test from the keyword; you could also put then on the next line.

Testing text with [[ ]]

[[ ... ]] is Bash's test command. The spaces just inside the brackets are required: [["$a" == "b"]] is an error.

2 exercises to try what you just read.

Exercise 1

Water state

Press Ctrl Enter or Check to test your code.

Exercise 2

File type guesser

Press Ctrl Enter or Check to test your code.

TestTrue when
[[ $a == $b ]]the strings are equal
[[ $a != $b ]]the strings differ
[[ -z $a ]]a is empty
[[ -n $a ]]a is not empty
[[ $a == y* ]]a matches the pattern (starts with y)

Inside [[ ]], an unquoted right side of == is a pattern: * matches anything, ? one character, and [abc] one of those characters. Quote it (== "y*") to compare literally. Also note that < and > inside [[ ]] compare text alphabetically, not as numbers, which is a classic bug.

You will also see the older single-bracket form [ ... ] (the test command) in scripts. It works, but it needs more careful quoting. In Bash, prefer [[ ]].

Comparing numbers with (( ))

For numbers, use arithmetic: (( )) succeeds when the expression is non-zero, so ordinary comparison operators just work:

Inside (( )) you can use ==, !=, <, <=, >, >=, and no $ is needed. The older style [[ $age -ge 18 ]], with -eq, -ne, -lt, -le, -gt and -ge, does the same thing.

Combining tests

Use && (and), || (or) and ! (not), inside a test or between commands:

&& and || between commands also work as a short if: [[ -z $name ]] && name="guest" sets a default only when name is empty.

case: matching one value against patterns

When you compare one value against many options, case is tidier than a chain of elif:

Each pattern ends with ), | separates alternatives, each branch ends with ;;, and * catches everything else. The first matching branch runs, and the block ends with esac.

Further reading

  • Bash manual: Conditional constructs (if, case, [[ ]], (( )))
  • Bash manual: Bash conditional expressions

Read a temperature in °C (a whole number) and print the state of water at that temperature:

  • ice below 0,
  • water from 0 up to 99,
  • steam at 100 or above.

Sample input:

Sample output:

Read a file name and print what kind of file it probably is, based on its ending:

  • .jpg, .jpeg or .png: image
  • .mp3 or .wav: audio
  • .txt or .md: text
  • anything else: unknown

If the line is empty, print no file name. Matching is case-sensitive.

Sample input:

Sample output:

if [[ "$answer" == "yes" ]]; then
    echo "Great!"
elif [[ "$answer" == "no" ]]; then
    echo "Maybe next time."
else
    echo "Please answer yes or no."
fi
if (( age >= 18 )); then
    echo "adult"
fi
if [[ -n $name && $name != "root" ]]; then echo "ok"; fi
if (( n > 0 && n % 2 == 0 )); then echo "positive and even"; fi
case "$day" in
    Sat|Sun)  echo "weekend" ;;
    Mon|Tue|Wed|Thu|Fri) echo "weekday" ;;
    *)        echo "not a day" ;;
esac
25
water
holiday.png
image