Skip to content

Exit status and conditional execution

Module
Input, Output and Pipes
Difficulty
Easy
Updated
Tested on
Ubuntu 24.04.5 LTS (lab container), GNU Bash 5.2.21
Prerequisites
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.

Finish Pipelines and tee (B09.3). Start with this empty disposable directory:

Terminal window
mkdir -p ~/lab/b09/status
cd ~/lab/b09/status

Use Reset this lesson before repeating the examples. Start with no files or subdirectories in this directory.

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:

Terminal window
test -f notes.txt
echo "$?"
Captured output from echo
1

The 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:

Terminal window
touch notes.txt
test -f notes.txt
echo "$?"
Captured output from echo
0

The 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:

Terminal window
ls missing.txt
Captured error output
ls: cannot access 'missing.txt': No such file or directory
Terminal window
echo "$?"
Captured output
2

The 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:

Terminal window
printf 'The next command changes the status\n'
echo "$?"
Captured output
The next command changes the status
0

That 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.

&& 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?

Terminal window
test -f notes.txt && printf 'Found\n'
echo "$?"
Run it, then compare with your guess
Captured output
Found
0

The 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.

Run the message when the file exists
learner@rootvolt:~/lab/b09/status$ test -f notes.txt && printf 'Found\n'Foundlearner@rootvolt:~/lab/b09/status$ echo "$?"0learner@rootvolt:~/lab/b09/status$ 

Step-by-step replay of a verified session · Recorded on Ubuntu 24.04.5 LTS, GNU Bash 5.2.21. With notes.txt present, the successful test permits printf, and the combined line returns 0.
Steps (6)
  1. Type test -f notes.txt && printf 'Found\n'
  2. Press Enter
  3. Output: Found
  4. Type echo "$?"
  5. Press Enter
  6. Output: 0

Make the condition false without deleting the note:

Terminal window
mv notes.txt saved.txt

This renames the file inside the disposable directory. saved.txt must not already exist; it does not exist in this lesson’s setup.

Terminal window
test -f notes.txt && printf 'Found\n'
echo "$?"
Captured output from echo
1

There 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.

|| 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?

Terminal window
test -f notes.txt || printf 'Not found\n'
printf 'status: %s\n' "$?"
Run it, then compare with your guess
Captured output
Not found
status: 0

No. 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.

Skip the success message and run a fallback
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$ 

Step-by-step replay of a verified session · Recorded on Ubuntu 24.04.5 LTS, GNU Bash 5.2.21. With notes.txt absent, && skips Found; || prints Not found, and the successful fallback leaves status 0.
Steps (11)
  1. Type test -f notes.txt && printf 'Found\n'
  2. Press Enter
  3. Type echo "$?"
  4. Press Enter
  5. Output: 1
  6. Type test -f notes.txt || printf 'Not found\n'
  7. Press Enter
  8. Output: Not found
  9. Type printf 'status: %s\n' "$?"
  10. Press Enter
  11. 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:

Terminal window
cat missing.log | wc -l
Captured output
cat: missing.log: No such file or directory
0
Terminal window
echo "$?"
Captured output
0

The 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.

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.

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
Terminal window
mkdir receipt
touch receipt.txt
ls -d receipt
echo "$?"
Captured output
receipt
0
Terminal window
test -f receipt
echo "$?"
Captured output
1

The directory exists, so the listing succeeds. It is not a regular file, so the file condition is false. Choose the fallback for that condition:

Terminal window
test -f receipt || printf 'Not a regular file\n'
echo "$?"
Captured output
Not a regular file
0
Terminal window
test -f receipt.txt && printf 'Receipt ready\n'
echo "$?"
Captured output
Receipt ready
0

The 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.

Terminal window
cd ~/lab/b09
ls -AR status
Terminal window
rm -r ~/lab/b09/status

Rerun Before you start. If the directory is already absent, skip removal.

  • Status 0 means 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.