Conditions and command tests
Quick answer
Use a command status to decide what an automation script does next. A successful status is zero; a nonzero status can mean a false test or an error.
Prepare the practice environment
Run python3 lab-fixtures/shell-scripting/setup.py as an ordinary user from the extracted package root in a disposable Linux environment. Enter the printed directory, check pwd, then run export LC_ALL=C; umask 077; set -o pipefail. Use a fresh fixture for each example. Save the code as example.sh inside that directory and run bash --noprofile --norc -o pipefail example.sh rather than sourcing it. Stop if a command fails unexpectedly. All output paths must be new. The source of check-report.sh is in the fixture JSON. Outputs below are not commands.
How it works
if command; then ...; else ...; fi branches on status. test -f PATH and [ -f "$path" ] check for a regular file; -d checks a directory and -n checks a nonempty string. Spaces around [ and ] are required. Bash also provides [[ ... ]] with different parsing rules. && runs the next command after success; || after failure. For operations that can fail, test the actual operation rather than relying on a preliminary existence check, which can become stale.
The shell branches on the command status, not on whether the command prints something. test -f absent.txt normally prints nothing and returns false. In the copy example, a successful cp only selects the success branch; the following cmp still has to succeed before the confirmation is printed. Avoid treating A && B || C as a general if/else replacement: C also runs if A succeeds but B fails.
Try the examples
if test -f notes.txt; then printf 'found\n'else printf 'missing\n'fiThe then branch runs because the fixture has a regular file.
Expected stdout:
foundif [ -f absent.txt ]; then printf 'found\n'else printf 'missing\n'fiA false test is an expected branch, not necessarily a script bug.
Expected stdout:
missingif cp -- notes.txt copy.txt; then cmp notes.txt copy.txt && printf 'copy verified\n'else printf 'copy failed\n' >&2 exit 1fiThe script checks the copy operation and compares bytes.
Expected stdout:
copy verifiedCommon mistakes
Do not interpret every nonzero exit as a crash. Never assume a preliminary file check guarantees a later operation will succeed.
Practice
Write a branch that checks notes.txt and absent.txt and explains both outcomes. Then test a real read operation.
Related references
Study: test, bash. These are reference names, not deployed links.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Conditions and command tests — Knowledge Check
Apply the lesson concepts to the controlled shell fixture.
What status selects the then branch?
Which test checks a regular file?
What does && do?
Why check the actual copy status?