Conditionals with if, test and double brackets

Beginner · 8 min

How if decides using an exit status, what [ ] and [[ ]] really are, the common file and string tests, and the string-versus-number traps.

Before thisExit status and && / || listsWord splitting and the order of expansion

You Suck at Programming · 8 min

Conditionals with if, test and double brackets

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by You Suck at ProgrammingReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `if` runs a command and branches on its exit status. It has no boolean type, so any command can be the condition.
  • `[ ... ]` is an ordinary command called `test`, so its arguments are subject to splitting, globbing and redirection. `[[ ... ]]` is shell syntax that avoids those problems.
  • Use `-f`, `-d`, `-r`, `-e` for files, `-z` and `-n` for empty and non-empty strings, `=` or `==` for string equality, and `-eq`, `-lt`, `-gt` for numbers.
  • Inside `[[ ]]`, `<` and `>` compare strings, so `[[ 10 < 9 ]]` is true. For numbers use `-lt` or `(( 10 < 9 ))`.
  • In `[[ ]]`, an unquoted right-hand side of `==` is a glob pattern and `=~` takes a regular expression. Quoting makes the right side literal.

A decision needs a question

A script has to react to things: does this file exist, did the count pass a limit, is the argument empty? You met && and || for one-line branches. For anything longer, you want if.

Here is the idea worth carrying forward. Bash’s if doesn’t evaluate a boolean expression. It runs a command and looks at the exit status from the previous lesson: zero takes the then branch, anything else moves on to elif or else.

$ if grep -q linus data/people.csv; then echo "found linus"; fi
found linus

grep -q is the condition. The conditions you see most often, though, use a command built for comparing things.

[ is a command

$ type [ ; type [[ ; ls -l /bin/[ | cut -c1-10
[ is a shell builtin
[[ is a shell keyword
-rwxr-xr-x

[ is a command, named like a punctuation mark, whose last argument must be ]. It also exists as the file /bin/[. It is also called test. Because it is an ordinary command, everything you learned about expansion applies to its arguments. They get split and globbed, and < and > become redirections.

[[ is different. It is a keyword, parsed by the shell itself before expansion. That’s why it can skip word splitting and give < its own meaning.

The tests you will use

For files: -e exists, -f regular file, -d directory, -r readable, -s non-empty. For strings: -z empty, -n non-empty, = equal, != not equal. For integers: -eq -ne -lt -le -gt -ge.

$ [ -f data/people.csv ] && echo "regular file"; [ -d data ] && echo "directory"
regular file
directory
$ [ "$name" = ada ] && echo "equal"; [ "$name" != bob ] && echo "not bob"
equal
not bob
$ [ 10 -gt 9 ] && echo "10 > 9 numerically"
10 > 9 numerically

Here is a full script, check.sh, using if, elif and else to inspect a log. ShellCheck reported nothing.

#!/usr/bin/env bash
log=${1:-logs/access.log}
if [[ ! -e $log ]]; then
  echo "no such file: $log"
elif [[ ! -s $log ]]; then
  echo "empty file: $log"
else
  errors=$(awk '$8 >= 500' "$log" | wc -l)
  if (( errors > 20 )); then
    echo "$errors server errors: too many"
  elif (( errors > 0 )); then
    echo "$errors server errors: a few"
  else
    echo "no server errors"
  fi
fi
$ ./check.sh; ./check.sh nope; ./check.sh empty.log
      24 server errors: too many
no such file: nope
empty file: empty.log

(The leading spaces on 24 come from BSD wc, the padding trap from the earlier lesson, left in because I didn’t wrap the count.)

The traps in single brackets

Unquoted empty variables vanish, so [ $x = y ] collapses to a malformed command:

$ x=; [ $x = y ] ; echo "status $?"
bash: [: =: unary operator expected
status 2
$ [[ $x = y ]]; echo "status $?"
status 1

Inside [ ], the redirect trap is worse. > is a redirect, so [ 10 > 9 ] runs [ 10 ] and writes nothing into a file called 9:

$ [ 10 > 9 ]; echo "status $?"; ls
status 0
9
check.sh
...

A test with one non-empty word is true, so it “passed” and left a file named 9 behind. [ 10 \< 9 ] is true too, since it compares as strings. ShellCheck flags it as SC2071, “> is for string comparisons. Use -gt instead”, and flags the unquoted [ $x = y ] as SC2086.

[[ 10 < 9 ]] behaves the same way, comparing strings and answering true, because "1" sorts before "9". Use -lt, or the arithmetic form (( 10 < 9 )), for numbers.

Why prefer [[

In Bash, [[ ]] removes most of those problems, and adds pattern matching and regexes:

$ f=report.txt; [[ $f == *.txt ]] && echo "glob match"; [[ $f == "*.txt" ]] || echo "quoted pattern is literal"
glob match
quoted pattern is literal
$ [[ $f =~ ^[a-z]+\.txt$ ]] && echo "regex match: ${BASH_REMATCH[0]}"
regex match: report.txt
$ [[ -f data/people.csv && -r data/people.csv ]] && echo "both"
both

You can combine tests with && and || inside [[ ]]. In single brackets, -a and -o also exist but are discouraged. [[ doesn’t exist in POSIX sh, so a script with a #!/bin/sh shebang meant to run on dash should stick to [ ], with quotes. The portability lesson comes back to this. I ran this whole set under both Bash 3.2 and 5.3 and got identical output.

About the video

“test vs [ vs [[: Bash Conditionals Explained!” is You Suck at Programming episode 66, 8 minutes 8 seconds, from August 2025, by Dave Eddy. The description is only links, so I could not check chapters, and I had no transcript. The title says it compares test, [ and [[, which is the same split this lesson makes. It is in English.

Where this fits

Conditions let a script choose once. To repeat work, you need loops, and to choose between many fixed values, case.

Check yourself

  1. 01What does `if grep -q linus people.csv; then ...` test?

    The exit status of `grep`. Status 0, meaning a match was found, runs the `then` branch. `if` can use any command as its condition, not only `[ ]`.

  2. 02Why does `[ 10 > 9 ]` always succeed, and what does it leave behind?

    The `>` is parsed as a redirect, so the shell runs `[ 10 ]` with output sent to a new file named `9`. A one-word test is true. Use `-gt` or `(( ))` for numbers.

  3. 03How do you test that a variable is empty without risking a syntax error?

    `[ -z "$var" ]` or `[[ -z $var ]]`. Unquoted inside single brackets, an empty variable disappears and the test is malformed.

  4. 04What do `[[ $f == *.txt ]]` and `[[ $f == "*.txt" ]]` do differently?

    The first treats `*.txt` as a glob pattern and matches any name ending in `.txt`. The quoted version compares against the literal five characters `*.txt`.

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark