← All lessons
Processes and scripts · Lesson 5 of 7

Decisions

if runs a command and checks its exit status: 0 counts as true. The usual command to check is [ ], the test command, which compares things and checks files. Spaces inside the brackets are required.

#!/bin/bash
if [ -f "$1" ]; then
  echo "$1 is a file"
elif [ -d "$1" ]; then
  echo "$1 is a folder"
else
  echo "No such thing: $1"
fi

The common tests: -f (a file exists), -d (a folder exists), -e (anything exists), -z (text is empty). Text is compared with = and !=. Numbers use letters: -eq (equal), -ne (not equal), -lt (less than), -gt (greater than), -le and -ge (or equal). ! turns a test around: [ ! -d backups ].

if [ "$#" -lt 1 ]; then
  echo "Usage: $0 name"
  exit 1
fi

For quick checks, chain commands. a && b runs b only if a succeeded; a || b runs b only if a failed. mkdir -p out && cd out changes into the folder only if it was made, and cd /data || exit 1 stops the script if the folder isn't there.

Bash also has [[ ]], which is more forgiving about quotes and adds pattern matching ([[ $file == *.jpg ]]). It's fine to use in Bash scripts; [ ] works in every shell.

Practice

Which test is true when notes.txt exists and is an ordinary file?

More info

Quick reference

if cmd; then … elif … else … fiRun a block when cmd succeeds.
[ -f x ], [ -d x ], [ -e x ]File, folder, anything exists.
[ -z "$s" ], [ "$a" = "$b" ]Empty text; equal text.
-eq -ne -lt -gt -le -geNumber comparisons.
!Not.
a && b, a || bb if a worked; b if a failed.

The other Linux courses