Chuyển đến nội dung

Bài 37 · Shell Scripting

Conditionals: if, test and [[ ]]

Learn Bash conditionals: if/elif/else, exit status as a condition, test, [ ] versus [[ ]], file, string and numeric tests, regex matching and common mistakes.

A script that does the same thing every time is a recipe. A script that decides is a program. In the shell, decisions are made by if, and the thing that surprises newcomers is what if actually looks at: not a true/false value, but the exit status of a command. Once you understand that, [ ], [[ ]], test, grep -q and (( )) stop looking like different features and become the same idea.

In this lesson you will learn the full if/elif/else syntax, why [ is really a command, the differences between [ ] and [[ ]], every test you will use in practice (files, strings, numbers), how to combine conditions with &&, || and !, how to match regular expressions, and the mistakes that cause most conditional bugs.

if looks at exit status

Every command ends with an exit status, a number from 0 to 255. By convention 0 means success and anything else means failure or "no" (see The Shell: Commands, Arguments and Options). The if statement runs a command, and if the status is 0 it takes the then branch:

TEXT
   if  COMMAND ; then        COMMAND is run; status 0 -> "true"
       BODY1                 non-zero -> go to the next elif / else
   elif COMMAND2 ; then
       BODY2
   else
       BODY3
   fi
Bash if with commands, not booleans

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

What this shows:

  • The condition can be any command. grep -q prints nothing and only reports "found" (status 0) or "not found" (status 1). true and false are real commands that do nothing except return 0 and 1.
  • ! negates the status. ! command is true when the command fails.
  • [ is a command, too. type -a shows that [ and test are both shell built-ins and programs in /usr/bin. [ "$n" -gt 5 ] is the command named [ called with the arguments "$n", -gt, 5 and a final ]. That is why the spaces around [ and ] are required: [$n -gt 5] would be the command [7, which does not exist.
  • (( )) is an arithmetic command whose status is 0 when the result is non-zero (see Arithmetic and Numbers).
  • The then can go on the same line after a semicolon, or on the next line. Both are the same. Always close with fi (if backwards).

If the condition command fails and there is no else, if itself finishes with status 0. A skipped if is not an error. This is important under set -e, and it means echo $? after an if does not tell you whether the condition was true.

test, [ ] and [[ ]]

There are three ways to write a test expression:

Form What it is Where it works
test EXPR A command (built-in and /usr/bin/test) Any POSIX shell
[ EXPR ] Exactly the same command, with a closing ] Any POSIX shell
[[ EXPR ]] A keyword with its own parser Bash, zsh, ksh (not plain sh)

Because [[ ]] is part of the shell's grammar, not a command, Bash can treat its contents specially:

  • No word splitting or globbing of unquoted variables inside, so [[ $name == "Ann Lee" ]] is safe even when $name contains spaces or is empty.
  • && and || work inside the brackets (with [ ] you must use -a/-o or separate tests).
  • == and != match glob patterns, and =~ matches regular expressions.
  • < and > compare strings without being mistaken for redirections.

In Bash scripts, use [[ ]]. Use [ ] only when a script must run under plain sh (see POSIX sh, Portability and Compatibility). Use (( )) for numbers.

File tests

The most common reason for a conditional in a script is to check a file before using it. The test operators start with a dash and a letter:

Test True when the path...
-e exists (any type)
-f is a regular file
-d is a directory
-L (or -h) is a symbolic link
-s exists and is not empty (size > 0)
-r / -w / -x is readable / writable / executable by you
a -nt b / a -ot b a is newer / older than b (by modification time)
a -ef b is the same file as b (same inode)
Bash File tests on different kinds of path

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Study the table of letters per row:

  • file.txt is e f s r w x: it exists, is a regular file, has content, and (after chmod +x) can be executed.
  • empty.txt has no s because its size is zero.
  • dir is a directory (d) and not a file (f); the x on a directory means you may enter it. See File Permissions and Ownership.
  • link has both f and L: most tests follow symbolic links, so the link counts as the regular file it points to. Only -L looks at the link itself. A dangling link would fail -e but pass -L. See Hard Links, Symbolic Links and Inodes.
  • missing.txt passes nothing.

A common idiom is "create the directory if it does not exist": [[ -d $dir ]] || mkdir -p "$dir" (although mkdir -p alone already does that).

The rest of the file-test operators

Besides the common ones, Bash has tests for special file types and permission bits. You will rarely need them every day, but scripts that inspect /dev, build FIFOs or audit permissions use them:

Test True when the path...
-b / -c is a block / character device (/dev/sda, /dev/null)
-p is a named pipe (FIFO, made with mkfifo)
-S is a socket
-h is a symbolic link (same as -L)
-k has the sticky bit (like /tmp)
-u / -g has the setuid / setgid bit
-O / -G is owned by your effective user ID / group ID
-N was modified since it was last read
-t N file descriptor N is open on a terminal ([[ -t 1 ]])

Combine them with && as usual, and remember that -g also marks directories that pass their group on to new files. The last one is useful in scripts: [[ -t 1 ]] is false when output is piped or redirected, so a script can print colours and progress bars only when a human is looking.

Bash Special file types, permission bits and -t

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

/dev/null is a character device and is not owned by you, so it has no O. link is reported as a symlink by -h and as owned by you because -O follows the link to the regular file. See File Permissions and Ownership for what setuid, setgid and the sticky bit do.

String tests

Test True when
-z "$s" the string is empty (zero length)
-n "$s" the string is not empty
[[ $a == $b ]] equal (right side is a glob pattern unless quoted)
[[ $a != $b ]] not equal
[[ $a < $b ]], > sorts before / after (string comparison, current locale)
[[ $a =~ regex ]] matches the extended regular expression

In [ ] use a single = for equality (a == works in Bash but is not POSIX). In [[ ]] both work; == is the common style.

Bash Strings, patterns and regular expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Three rules to remember:

  1. Quoting the right-hand side switches pattern matching off. [[ $s == h* ]] is a glob match, [[ $s == "h*" ]] compares with the literal text h*.
  2. For =~, put complicated regular expressions in a variable (re='...') and use it unquoted: [[ $v =~ $re ]]. A quoted regex is matched literally, and a regex written inline must avoid unescaped spaces and shell-special characters. Groups land in the array BASH_REMATCH ([0] is the whole match). More about expressions in Regular Expressions for the Shell.
  3. =~ uses extended regex syntax, with intervals. [[ ]] is a Bash feature, so it does not suffer from the missing support of the older awk in our sandbox.

Number tests

Inside [ ] and [[ ]], numbers are compared with words, not symbols, because < and > already mean something else:

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

The alternative is (( )), where the usual symbols work ((( n >= 10 ))). Use whichever reads best; (( )) is shorter and does not need $. Remember the string-versus-number trap: [[ 10 < 9 ]] is a string comparison (and is true, because 1 sorts before 9), while (( 10 < 9 )) is false.

Bash Numbers, strings and combining tests

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The last test shows that numeric operators accept integers only: 5.0 produces the error [[: 5.0: syntax error: invalid arithmetic operator (error token is ".0"). The [[ command fails with a status of 1, which the script can still handle like any other "false".

Combining conditions

You have three ways to combine tests:

  • Inside [[ ]]: &&, ||, ! and parentheses: [[ -f $f && -r $f ]].
  • Between commands: cmd1 && cmd2 runs cmd2 only if cmd1 succeeds. cmd1 || cmd2 runs cmd2 only if cmd1 fails. [[ -d $d ]] || mkdir "$d" and command -v git >/dev/null && echo "git found" are typical.
  • Several ifs for readability. If you need an else branch, if is clearer than a long &&/|| chain.

A subtle point: a && b || c is not the same as if a; then b; else c; fi. If a succeeds but b fails, c runs too. Use &&/|| for simple one-liners and if otherwise.

The classic mistakes

All of these produce real, confusing messages. The example below shows several with [ ]:

Bash Mistakes with [ ] (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Explanations, in order:

  1. Unquoted variable in [ ]. [ $x = "two words" ] becomes [ two words = "two words" ]: too many arguments. The error is [: too many arguments. And look: echo "status: $?" prints 0, because the failed test made if skip the body, and a skipped if has status 0.
  2. Empty variable. [ $y = "" ] becomes [ = "" ], giving [: =: unary operator expected. Always quote variables in [ ], or switch to [[ ]].
  3. [ -n $y ] with an empty y becomes [ -n ], a one-argument test, which means "is the string -n non-empty?" and so is true. Another reason to quote.
  4. [ 5 > 3 ] is not a comparison. The shell sees > as a redirection and creates a file named 3! ls at the end shows it. The test [ 5 ] succeeds (a non-empty string is true), so hi is printed. Use -gt, (( 5 > 3 )) or [[ ]].
  5. Missing spaces: [ $a -eq $b] and if [$a -eq $b] fail, because ] and [ are separate words.
  6. Using = for assignment spacing: x = 5 runs a command named x. Assignments have no spaces, comparisons do.

When you are unsure whether a string is a clean integer before a numeric test, check it first with a regex: [[ $v =~ ^-?[0-9]+$ ]] && (( v > 10 )). That avoids the error message of -gt on text.

When to use what

  • Existence, type and permission of files: [[ -f ... ]], [[ -d ... ]], [[ -r ... ]].
  • Comparing numbers: (( )) for arithmetic style, or -eq/-lt in [[ ]].
  • Strings and patterns: [[ ]] with == and =~. For many alternatives on one value, a case statement is neater: case Statements and Menus.
  • "Did this command work?": use the command itself as the condition, if mkdir "$d"; then ..., instead of running it and testing $? afterwards.
  • Portable scripts: [ ] with quoted variables and =.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What does if evaluate to decide which branch to run?

    The condition is a command. Exit status 0 counts as success and runs the then branch; any other status goes to elif or else.
  2. 2. Why does [ $name = Ann ] fail with an error when name is empty?

    Without quotes the empty expansion vanishes and the test gets too few arguments (unary operator expected). Quote the variable or use [[ ]].
  3. 3. What does [ 5 > 3 ] actually do?

    In [ ] the > is a redirection operator. The shell creates a file named 3, and the test [ 5 ] is true because a non-empty string is true. Use -gt or (( )).
  4. 4. In [[ $s == "h*" ]], what does the quoted right-hand side mean?

    Quoting disables pattern matching in the right-hand side of == and !=, so the string is compared literally.
  5. 5. Which test is true for a symbolic link that points to a regular file?

    Most file tests follow the link, so -f sees the regular file it points to, while -L tests the link itself. Both are true.

Summary

  • if runs a command and branches on its exit status: 0 means true. ! negates, && and || combine, and a skipped if has status 0.
  • [ and test are commands (spaces required); [[ ]] is a Bash keyword without word splitting, with &&, ||, patterns (==) and regex (=~, results in BASH_REMATCH).
  • Quote variables in [ ]; in [[ ]] quote the right-hand side only when you want a literal match.
  • File tests: -e -f -d -L -s -r -w -x, -nt, -ot, -ef. Most follow symbolic links. Also -b -c -p -S -h -k -u -g -O -G -N and -t FD (is it a terminal?).
  • Numbers: -eq -ne -lt -le -gt -ge, or (( )) with symbols. < and > inside [[ ]] compare strings.
  • Never write [ a > b ]: it creates a file.
  • Prefer if command; then over testing $? afterwards.

Next: case Statements and Menus

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.