Exit status and conditional execution
On this page
A file check prints nothing and returns to the prompt. You cannot tell from that empty result whether it found the file. Before choosing the next action, you need a result that does not depend on a printed message.
By the end, you can inspect that result, distinguish a false check from another command’s error, and run a message only when the preceding command succeeds or fails.
Before you start
Section titled “Before you start”Finish Pipelines and tee (B09.3). Start with this empty disposable directory:
mkdir -p ~/lab/b09/statuscd ~/lab/b09/statusUse Reset this lesson before repeating the examples. Start with no files or subdirectories in this directory.
Read a result that prints nothing
Section titled “Read a result that prints nothing”test -f NAME checks whether NAME exists and is a regular file. test is a command; -f selects this particular check. It reports its answer through an exit status, the number a command returns when it finishes.
Run the check, then inspect its status immediately:
test -f notes.txtecho "$?"1The test printed nothing. $? is Bash’s special parameter holding the most recent foreground pipeline’s status. For a single command such as this test, it gives that command’s result. The double quotes allow expansion, as they did for variables in B08.3.
Status 0 means success. A nonzero status means a result other than success, with its particular meaning defined by the command. Here test returns 1 because the file condition is false. That is an expected answer to a question, without a diagnostic or a broken program.
Create the empty file with touch from B06.1:
touch notes.txttest -f notes.txtecho "$?"0The condition is true. Empty contents do not make it false: this check asks whether a regular file exists, not whether it contains text.
Interpret the number for the command that returned it
Section titled “Interpret the number for the command that returned it”Compare a failed listing:
ls missing.txtls: cannot access 'missing.txt': No such file or directoryecho "$?"2The missing-path invocation of GNU ls returns 2. Its manual defines 0 as success, 1 for minor problems, and 2 for serious trouble such as an inaccessible command-line argument. Those meanings belong to ls. Bash does not assign the meaning “missing file” to every status 2 from every program.
| Captured command | Status | Meaning for that command |
|---|---|---|
test -f notes.txt, before creation |
1 |
The file condition is false |
test -f notes.txt, after creation |
0 |
The file condition is true |
ls missing.txt |
2 |
GNU ls cannot access its command-line argument |
Consult each command’s manual when the particular nonzero number matters. For Bash’s builtin test, use help test or man bash. A diagnostic explains a problem in words; the status lets the shell choose what to run next.
Read $? before running an unrelated command. For example, after the failed listing:
printf 'The next command changes the status\n'echo "$?"The next command changes the status0That 0 belongs to the successful printf, not the earlier ls. Printing $? also runs a command: a second inspection would describe the first inspection’s success.
Run the next command only on success
Section titled “Run the next command only on success”&& runs the command on its right only if the command on its left returns status 0. Keep the existing notes.txt for this first run.
Predict first: does this line print Found because test prints a filename, or because its status is 0?
test -f notes.txt && printf 'Found\n'echo "$?"Run it, then compare with your guess
Found0The status decides. test itself prints nothing. Its success permits printf to run, and that command prints Found and succeeds. The combined line’s status is the status of its last executed command, here printf.
learner@rootvolt:~/lab/b09/status$ test -f notes.txt && printf 'Found\n'Foundlearner@rootvolt:~/lab/b09/status$ echo "$?"0learner@rootvolt:~/lab/b09/status$ Steps (6)
- Type
test -f notes.txt && printf 'Found\n' - Press Enter
- Output:
Found - Type
echo "$?" - Press Enter
- Output:
0
Make the condition false without deleting the note:
mv notes.txt saved.txtThis renames the file inside the disposable directory. saved.txt must not already exist; it does not exist in this lesson’s setup.
test -f notes.txt && printf 'Found\n'echo "$?"1There is no Found line. The test returns 1, so Bash skips printf. The last command actually executed on that combined line is the false test, and its status remains 1.
Run a fallback only on nonzero status
Section titled “Run a fallback only on nonzero status”|| runs the command on its right only if the left command returns nonzero. Leave notes.txt absent.
Predict first: after the fallback prints successfully, does the whole line retain the test’s status 1?
test -f notes.txt || printf 'Not found\n'printf 'status: %s\n' "$?"Run it, then compare with your guess
Not foundstatus: 0No. The false test permits the fallback. The fallback printf succeeds, so the combined line ends with status 0. Its printed words describe the missing file; its status describes the successful message command.
learner@rootvolt:~/lab/b09/status$ test -f notes.txt && printf 'Found\n'learner@rootvolt:~/lab/b09/status$ echo "$?"1learner@rootvolt:~/lab/b09/status$ test -f notes.txt || printf 'Not found\n'Not foundlearner@rootvolt:~/lab/b09/status$ printf 'status: %s\n' "$?"status: 0learner@rootvolt:~/lab/b09/status$ Steps (11)
- Type
test -f notes.txt && printf 'Found\n' - Press Enter
- Type
echo "$?" - Press Enter
- Output:
1 - Type
test -f notes.txt || printf 'Not found\n' - Press Enter
- Output:
Not found - Type
printf 'status: %s\n' "$?" - Press Enter
- Output:
status: 0
|| responds to any nonzero status from its left command, not only one particular number. Use these short two-command forms when the outcome has a clear next action. A longer mixture of && and || needs care: a right-hand command can itself fail. It is not automatically a general replacement for a conditional construct.
Know which pipeline result you are checking
Section titled “Know which pipeline result you are checking”Under the Bash defaults used in this course, a pipeline’s status is its last command’s status. The failing cat example from B09.3 makes the limit visible:
cat missing.log | wc -lcat: missing.log: No such file or directory0echo "$?"0The first 0 is wc’s printed count. The second is its successful status. cat failed, but wc successfully counted the empty input it received. A successful final stage therefore does not establish that every earlier stage succeeded. Check the input and diagnostics as well; this lesson does not change shell options.
Mistakes to recognize
Section titled “Mistakes to recognize”Using silence as a success check. A false test is silent too. Inspect its status or connect the intended next command with && or ||.
Inspecting too late. ls, printf, and even a status-printing command can replace the result you wanted. Read $? immediately.
Treating every nonzero status as the same error. The captured 1 from test means false; the captured 2 from ls describes trouble accessing its argument. Read that command’s documentation.
Try it yourself
Section titled “Try it yourself”Goal: Create a directory called receipt and an empty regular file called receipt.txt. Prove that listing receipt succeeds but testing it with -f returns false. Print Not a regular file only for that false test, and Receipt ready only for a successful regular-file check of receipt.txt. Inspect the status after every check and combined line.
Explain why the directory’s existence does not make test -f receipt succeed. This time the false condition must not depend on a missing name.
Hint
ls -d lists the directory itself, using the -d option from B05.3. The -f test asks about a regular file, rather than any kind of existing name. Use a separate && or || line for each message.
Solution
mkdir receipttouch receipt.txtls -d receiptecho "$?"receipt0test -f receiptecho "$?"1The directory exists, so the listing succeeds. It is not a regular file, so the file condition is false. Choose the fallback for that condition:
test -f receipt || printf 'Not a regular file\n'echo "$?"Not a regular file0test -f receipt.txt && printf 'Receipt ready\n'echo "$?"Receipt ready0The tests have different results, but each permits a successful message in its chosen form. Both combined lines end at 0; neither result makes the directory a regular file.
Reset this lesson
Section titled “Reset this lesson”cd ~/lab/b09ls -AR statusrm -r ~/lab/b09/statusRerun Before you start. If the directory is already absent, skip removal.
- Status
0means success; a nonzero number has the meaning defined by its command. $?holds the last foreground pipeline’s status. Inspect it immediately.&&runs the right command on success;||runs it on nonzero status. The last executed command supplies the combined result.- With the tested defaults, a pipeline reports its last command’s status, which does not prove all stages succeeded.
Next, Practice: Input, Output and Pipes combines stream routing, saved text, pipelines, and status checks.
Further reading
Section titled “Further reading”- On your system:
help test,man bash, andman ls, section Exit status. - GNU Bash: Exit Status, Lists of Commands, and Pipelines.
- Ubuntu 24.04: bash(1) and ls(1).