Skip to the workspace
Pebellslearn by building
Exit Codes and Conditionals  ›  Lesson

if and the [[ ]] Test

if 15 minif runs a command and takes the then branch when its exit status is zero, and the [[ ]] test compares strings, numbers and files.

shell bash / if and the [[ ]] Test

Explore each scene at your own pace.

01 · The rule

The rule

if and the [[ ]] Test

if runs a command and takes the then branch when its exit status is zero, and the [[ ]] test compares strings, numbers and files.

Choose the branch from an exit status and use the appropriate string or numeric test.

Run backup.sh with no argument and it happily archives an empty path. Run it with a typo and tar fails halfway. A careful script checks its input first and refuses politely. That needs a way to choose between actions.

The rule

if runs a command; status zero takes the then branch.

if [[ $# -lt 1 ]]; then
    echo "Usage: $0 SOURCE [NAME]" >&2
    exit 2
fi

src="$1"
if [[ ! -d "$src" ]]; then
    echo "Not a folder: $src" >&2
    exit 1
elif [[ ! -r "$src" ]]; then
    echo "Cannot read: $src" >&2
    exit 1
else
    echo "Backing up $src"
fi

(>&2 sends a message to standard error, so it does not mix with real output.)

if does not test "true or false" in the abstract. It runs a command and looks at its exit status. [[ ... ]] is simply a command whose status is 0 when the test inside holds. So any command works:

if tar -czf "$archive" "$src"; then echo "Saved"; fi
if grep -q ERROR log.txt; then echo "Errors found"; fi

The tests you will use most inside [[ ]]:

Kind Operators
Strings == != equal, not equal; -z empty; -n not empty
Numbers -eq -ne -lt -le -gt -ge
Files -e exists, -f regular file, -d directory, -r -w -x readable, writable, executable, -s not empty
Negation ! in front of a test

For numbers you can also use arithmetic: if (( count > 10 )); then. Older scripts use single brackets [ ... ], which work in any POSIX shell but are fussier: variables must be quoted inside them.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.