C.W.K.
Stream
Lesson 03 of 12 · published

Conditionals: if/elif/else and [[ ]]

~12 min · if, test, comparison

Level 0Window Tourist
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

The shape

if [[ condition ]]; then
  # ...
elif [[ other ]]; then
  # ...
else
  # ...
fi

if takes a command. It runs the command and branches on exit code (0 = then, non-zero = else). [[ ... ]] is the bash/zsh test command — preferred over [ ... ] (POSIX) because it's safer with empty variables and supports more operators.

String tests

  • [[ -z "$x" ]] — string is empty.
  • [[ -n "$x" ]] — string is non-empty.
  • [[ "$a" == "$b" ]] — equal.
  • [[ "$a" != "$b" ]] — not equal.
  • [[ "$x" == prefix* ]] — glob match (only inside [[ ]]).
  • [[ "$x" =~ ^[0-9]+$ ]] — regex match (bash/zsh).

Numeric tests

  • [[ $a -eq $b ]] — equal (eq, ne, lt, le, gt, ge).
  • (( a == b )) — arithmetic context (cleaner for math).

File tests

  • [[ -f path ]] — regular file exists.
  • [[ -d path ]] — directory.
  • [[ -e path ]] — exists (any type).
  • [[ -r path ]], -w, -x — readable / writable / executable.
  • [[ -s path ]] — exists and non-empty.

And / or

if [[ -f config.yaml && -r config.yaml ]]; then ...
if [[ -z "$NAME" || -z "$EMAIL" ]]; then ...

Inside [[ ]], use && and ||. Outside it, those operators chain whole commands.

Code

Practical conditionals·bash
#!/usr/bin/env bash
set -euo pipefail
config=~/.config/myapp/config.yaml
if [[ -f "$config" && -r "$config" ]]; then
  echo "using $config"
elif [[ -n "${MYAPP_FALLBACK:-}" ]]; then
  echo "using fallback $MYAPP_FALLBACK"
else
  echo 'no config' >&2
  exit 1
fi

External links

Exercise

Write a script that checks [[ -f $1 ]] and reports whether the path is a regular file. Test with an existing file, a directory, and a missing path. Add [[ -s $1 ]] to also require non-empty.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.