TExcelTAD
Home › Linux & Bash › if/else & test

if/else & test

if runs commands only when a condition is true. In Bash a "condition" is simply a command: if it exits with status 0 (success), the condition is true. Tests like "is this file there?" or "is x greater than 5?" are themselves commands: test, [ ] and [[ ]].

The if statement

bash · try it yourself
score=72
if [ "$score" -ge 50 ]; then
  echo "passed"
fi

if [ "$score" -ge 90 ]; then
  echo "grade A"
elif [ "$score" -ge 70 ]; then
  echo "grade B"
else
  echo "grade C"
fi
passed
grade B

Syntax rules: then follows the condition (after ; or a newline), elif and else are optional, and the block ends with fi (if backwards). The spaces inside [ and ] are required: [ is a command and ] its last argument.

Any command works as a condition

bash · try it yourself
printf 'ada\nlinus\n' > users.txt
if grep -q '^ada
  

 users.txt; then
  echo "ada has an account"
fi
if ! mkdir users.txt 2>/dev/null; then
  echo "could not create a directory named users.txt"
fi
if cd /etc; then echo "now in $PWD"; fi
ada has an account
could not create a directory named users.txt
now in /etc

! negates the exit status. Writing if grep ... is much cleaner than running grep and then checking $?.

Numeric comparisons

Inside [ ] and [[ ]], numbers are compared with letter operators (because > and < mean redirection):

Operator Meaning
-eq / -ne equal / not equal
-lt / -le less than / less or equal
-gt / -ge greater than / greater or equal

For arithmetic there's also (( )), where you can use normal symbols:

bash · try it yourself
disk_used=91
if (( disk_used > 90 )); then echo "critical"; fi
files=0
(( files == 0 )) && echo "no files yet"
if [ 10 -gt 9 ]; then echo "10 > 9 numerically"; fi
if [[ 10 > 9 ]]; then echo "string compare says 10 > 9"; else echo "string compare: '10' sorts before '9'"; fi
critical
no files yet
10 > 9 numerically
string compare: '10' sorts before '9'

The last line is a classic trap: inside [[ ]], > compares strings alphabetically, and "10" sorts before "9".

String tests

Test True when
[ "$a" = "$b" ] Strings equal (== also works in [[ ]])
[ "$a" != "$b" ] Not equal
[ -z "$a" ] Empty string
[ -n "$a" ] Non-empty string
[[ $a == pat* ]] Glob match (only in [[ ]])
[[ $a =~ regex ]] Regex match (only in [[ ]])

File tests

Test True when the path…
-e exists
-f is a regular file
-d is a directory
-s is a file that's not empty
-r / -w / -x is readable / writable / executable
-L is a symbolic link
a -nt b a is newer than b
bash · try it yourself
mkdir -p logs
touch logs/empty.log
echo "data" > config.ini
for path in config.ini logs logs/empty.log missing.txt; do
  if [ -d "$path" ]; then kind="directory"
  elif [ -s "$path" ]; then kind="file with content"
  elif [ -f "$path" ]; then kind="empty file"
  else kind="does not exist"
  fi
  printf '%-16s %s\n' "$path" "$kind"
done
config.ini       file with content
logs             directory
logs/empty.log   empty file
missing.txt      does not exist

Combining conditions

In [[ ]] In [ ] Between commands
&& and -a (obsolete) cmd1 && cmd2
|| or -o (obsolete) cmd1 || cmd2
! not ! ! cmd
bash · try it yourself
user="ada"; role="admin"
if [[ $user == "ada" && $role == "admin" ]]; then echo "full access"; fi
if [ "$role" = "guest" ] || [ "$role" = "viewer" ]; then echo "read-only"; else echo "can write"; fi
[[ -f /etc/passwd && ! -w /etc/passwd ]] && echo "/etc/passwd exists and is not writable by $user"
full access
can write
/etc/passwd exists and is not writable by ada

[ ] versus [[ ]]

[ (also called test) is the portable POSIX command. [[ ]] is Bash syntax with extras: no word splitting of variables, &&/|| inside, pattern and regex matching. In Bash scripts, prefer [[ ]] for strings and (( )) for numbers.

bash · try it yourself
name=""
[ $name = "admin" ] && echo "admin"
[[ $name = "admin" ]] || echo "[[ ]] copes with the empty variable"
/w/main.sh: line 2: [: =: unary operator expected
[[ ]] copes with the empty variable

With [ ], the unquoted empty variable vanished and [ saw = admin, a broken expression. Quoting ("$name") fixes it; [[ ]] doesn't need it.

Test yourself

What does if actually check?

  1. Whether the condition prints true
  2. The exit status of the condition command (0 = true)
  3. Whether a variable is set
  4. The output length

Which test is true when $dir is an existing directory?

  1. [ -f "$dir" ]
  2. [ -d "$dir" ]
  3. [ -e -d $dir ]
  4. [ -s "$dir" ]

Why is [[ 10 > 9 ]] false?

  1. It's a syntax error
  2. > inside [[ ]] compares strings, and "10" sorts before "9"
  3. Bash can't compare numbers
  4. It redirects to a file named 9