LESSON · 1 OF 5

if and test

if and test

The most common decision shape in shell scripts:

bash
if command; then
  ...
elif command; then
  ...
else
  ...
fi

if doesn't check a boolean. It checks whether the command succeeded. Exit code 0 (success) means the then branch runs, nonzero means skip to elif or else.

The test command

Comparing values needs a command that returns 0 or nonzero based on the comparison. That command is test, or its more common alias [.

bash
if [ "$user" = "root" ]; then
  echo "hi root"
fi

Read [ ... ] as "test whether...". The closing ] is required. Spaces around [ and inside are mandatory.

Common test operators

Strings:

  • [ "$a" = "$b" ] equal
  • [ "$a" != "$b" ] not equal
  • [ -z "$a" ] empty
  • [ -n "$a" ] non-empty

Numbers:

  • [ "$a" -eq "$b" ] equal
  • [ "$a" -ne "$b" ] not equal
  • [ "$a" -lt "$b" ] less than
  • [ "$a" -le "$b" ] less than or equal
  • [ "$a" -gt "$b" ], [ "$a" -ge "$b" ] greater

Files:

  • [ -f file ] regular file exists
  • [ -d dir ] directory exists
  • [ -e path ] anything exists
  • [ -r file ] readable
  • [ -w file ] writable
  • [ -x file ] executable

Why quote everything

bash
name=""
if [ $name = "alice" ]; then    # syntax error: [ = alice ]

Unquoted $name when empty expands to nothing, breaking the test syntax. Always quote both sides:

bash
if [ "$name" = "alice" ]; then

The next node shows a safer alternative that fixes this whole class of bug.

Spin up a fresh environment and practice live.
linux-devops-basic · fresh machine · ready in under a minute