Bash Tutorial · Bash Scripting · Lesson 17 of 30

Bash Conditionals: if, [[ ]] and case

Make decisions with if, test strings, numbers and files with [[ ]], and match patterns with case.

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

if and [[ ]]

if runs a command and checks its exit status (0 means true). [[ ... ]] is Bash's test command:

Test True when
[[ $a == "$b" ]], != strings equal / differ
[[ -z $s ]], [[ -n $s ]] string empty / not empty
(( n > 5 )) or [[ $n -gt 5 ]] numeric comparison
[[ -f path ]], -d, -e, -r, -x file exists / directory / exists / readable / executable
[[ $s == *.log ]], [[ $s =~ ^[0-9]+$ ]] glob match / regex match

Combine with &&, || and !.

if with file, regex and numeric tests
touch config.yml
for f in config.yml missing.yml; do
  if [[ -f $f ]]; then
    echo "$f exists"
  else
    echo "$f is missing"
  fi
done
input="42"
if [[ $input =~ ^[0-9]+$ ]] && (( input > 10 )); then
  echo "$input is a number greater than 10"
fi

Output

config.yml exists
missing.yml is missing
42 is a number greater than 10

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

case

case matches a value against patterns, which is cleaner than long if/elif chains:

case with patterns
for file in report.csv photo.JPG notes.txt archive.tar.gz; do
  case "$file" in
    *.csv) echo "$file: spreadsheet" ;;
    *.jpg|*.JPG|*.png) echo "$file: image" ;;
    *.tar.gz) echo "$file: archive" ;;
    *) echo "$file: other" ;;
  esac
done

Output

report.csv: spreadsheet
photo.JPG: image
notes.txt: other
archive.tar.gz: archive

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

Test yourself

What does if check in Bash?

  1. Whether the output is non-empty
  2. The exit status of the command (0 means true)
  3. Whether a variable is set
  4. A boolean variable
Show answer

Answer: The exit status of the command (0 means true)

Was this page helpful?