Linux › Section K · Shell scripts › Topic K.3
Conditionals
Scripts earn their keep by making decisions: skip a file that is missing, refuse a bad option, act only when a pattern is found. In the shell every decision rests on one thing, the exit code of a command, and once you see that, if, test and case stop being mysterious.
Decisions run on exit codes
Most languages test a true-or-false expression. The shell tests a command: if runs the command after it and checks its exit code, from "Special variables and exit codes". Status 0 counts as true, anything else as false. 1. Run the command after if. 2. If its status is 0, run the commands after then, up to else, elif or fi. 3. Otherwise, run the commands after else, if there is one. 4. Continue after fi, the word that closes the conditional. The words if, then, else, elif and fi are shell keywords; everything between them is ordinary commands.
The [ command
The usual condition looks like special syntax but is a command named [, also called test; its last argument must be ]. In bash, type [ reports [ is a shell builtin, and a standalone /usr/bin/[ exists too. Because [ is a command, spaces matter: [ "$1" = hi ] is [ with four arguments, while ["$1" = hi] is not. The semicolon in if [ "$1" = hi ]; then ends the command so that then can follow on the same line. Leave it out and then becomes one more argument to [; bash reaches fi without finding a then and stops with syntax error near unexpected token `fi'. Putting then on its own line also works.
Worked example: the missing argument bug
A script greet.sh contains if [ $1 = hi ]; then echo 'You said hi'; else echo "You said: $1"; fi (written over several lines). 1. sh greet.sh hi prints You said hi, and sh greet.sh bye prints You said: bye. 2. With no argument, where sh is bash, it prints greet.sh: line 2: [: =: unary operator expected, then You said: with nothing after it. 3. Why: the empty, unquoted $1 vanishes, so [ receives only = hi ], which is not a valid test. [ fails with a non-zero status, so the else branch runs. 4. Fix it by quoting: [ "$1" = hi ]. Now [ compares an empty string with hi, the test is simply false, and the run prints You said: with no error. Older scripts write [ x"$1" = xhi ] for the same reason.
Any command can be a test
Any command works as a condition: if grep -q data full.txt; then echo found; fi uses grep's quiet mode, which prints nothing and returns 0 for a match. Two one-line forms help too. In cmd1 && cmd2, cmd2 runs only if cmd1 succeeds; in cmd1 || cmd2, it runs only if cmd1 fails. So [ -d backup ] || mkdir backup creates the directory only when it is missing. Such a list's status is that of the last command actually run. To join tests, write [ "$1" = hi ] || [ "$1" = hello ]; the older -a and -o operators inside one [ were marked obsolescent by POSIX, then removed in its 2024 edition. A ! in front inverts a test: [ ! -f notes.txt ].
elif: more than two branches
elif adds further tests to one if, and the shell takes only the first branch whose test succeeds. A script hb.sh tests whether $1 is hi or hello, then elif [ "$1" = bye ], then elif [ -z "$1" ], then else. Results: hi and hello print Greeting: hi and Greeting: hello, bye prints Farewell, an empty argument prints No argument, and what prints Unknown: what. Put the most specific tests first, because later branches are skipped once one matches. When elif tests compare one value against many strings, case is usually clearer.
File tests
Most [ tests ask about files, which is what scripts handle best. -e is true if the path exists at all, -f if it is a regular file, -d if it is a directory, and -s if it exists and is not empty. In a test, an empty file passed -e and -f but failed -s, and a missing name passed none. Others check type (-h symbolic link, -b and -c block and character device, -p named pipe, -S socket) or permission (-r, -w, -x: readable, writable, executable by you). Except for -h, tests follow a symbolic link to its target. Two files can be compared: [ new.txt -nt old.txt ] is true when new.txt was modified more recently, and -ot is the reverse.
String and number tests
= and != compare strings; -z is true for an empty string and -n for a non-empty one. Numbers need their own operators: -eq, -ne, -lt, -le, -gt and -ge. Mixing them up gives wrong answers silently. [ 01 = 1 ] is false, because the strings differ, but [ 01 -eq 1 ] is true. [ 10 \< 9 ] is true, because it compares strings and the character 1 sorts before 9, while [ 10 -lt 9 ] is false. A non-number fails loudly: [ abc -eq 1 ] prints integer expression expected and returns 2. One more trap: with x empty, unquoted [ -n $x ] returns 0, true, because [ sees a single argument, -n, and treats it as a non-empty string. Quoted, [ -n "$x" ] correctly returns 1.
Worked example: a case dispatcher
case matches one word against glob patterns, with no exit codes involved. A script cs.sh begins case $1 in and lists: start|begin) echo Starting ;; then stop) echo Stopping ;; then *.log) for any name ending in .log, then ?) for any single character, then *) which prints a usage message to standard error and runs exit 2, and finally esac. 1. sh cs.sh start and sh cs.sh begin both print Starting, because | separates alternatives. 2. sh cs.sh app.log prints A log file: app.log. 3. sh cs.sh x prints One character. 4. sh cs.sh restart matches nothing earlier, reaches *, prints Usage: cs.sh start|stop and exits with status 2. 5. Check the order: the first matching pattern runs, and its ;; jumps to esac, so the catch-all * must come last.
bash extras: [[ ]] and (( ))
bash adds two constructs that sh does not guarantee. [[ ]] is a keyword, not a command, so unquoted empty variables do not vanish inside it, and == on its right side matches a glob pattern: [[ report.txt == *.txt ]] is true. Its < and > still compare strings, so [[ 10 < 9 ]] is true. (( )) does arithmetic tests with familiar operators: with n=7, (( n > 5 )) is true and (( 10 < 9 )) is false. Use them only under #!/bin/bash: dash, the /bin/sh of Debian and Ubuntu, lacks them.
Common mistakes to avoid
First, missing spaces inside [ ], or no semicolon before a then on the same line. Second, unquoted variables, which break tests when a value is empty. Third, comparing numbers with = or <. Fourth, writing if [ grep -q x file ] when you mean if grep -q x file; the command is the test. Fifth, putting the catch-all * first in a case, or forgetting ;;. Sixth, using [[ ]] or (( )) in a script whose shebang is #!/bin/sh.
Key takeaways
if runs a command and treats status 0 as true; elif and else add branches and fi ends the block. [ is the test command, so it needs spaces and a closing ]. Use -e, -f, -d, -s, -r, -w, -x and -nt for files, =, !=, -z and -n for strings, and -eq to -ge for numbers, and quote variables. && and || run a second command on success or failure. In case, the first matching pattern wins and each branch ends with ;;. bash adds [[ ]] and (( )).
Flashcards
Flashcard
Runs the then branch when cmd exits with status 0
Test your understanding
Question 1 of 5
A script tests if [ $1 = hi ]; then and is run with no arguments. What happens?
Question 2 of 5
Which test is true?
Question 3 of 5
What does the command [ -d backup ] || mkdir backup do?
Question 4 of 5
A case block lists *) echo unknown ;; first and start) echo Starting ;; second. What does the script print for the argument start?
Question 5 of 5
Why does if [ "$1" = hi ] then, with then on the same line and no semicolon, fail?
