$
Learn Linux handbook
en
XP:0

Chapter 12 of 17

Write predictable Bash scripts

Move from command sequences to programs with inputs, decisions, and observable failures.

The mental model.

A shebang such as #!/usr/bin/env bash selects an interpreter when an executable script is launched directly. bash script.sh explicitly chooses Bash and does not require the executable bit. Running a script as a child process does not change the parent shell’s directory or variables.

Quote expansions such as "$1" and "$file" to preserve spaces and prevent unintended globbing. "$@" preserves each argument separately. Single quotes preserve literal text; double quotes allow parameter and command expansion.

Exit status 0 means success; nonzero indicates a failure or other condition. grep uses 1 for no match and 2 for an error. && runs the next command on success; || runs it on failure. In Bash, pipefail changes how pipeline failure is reported.

Validate arguments, use explicit error handling, and clean up temporary resources with trap. set -e has context-dependent exceptions and is not a substitute for understanding failures. Cron runs with a small environment: use explicit paths and capture output.

Read it. Predict it. Try it.

Before running these commands, predict what each line will change or print. Launch a quest below to open the simulated terminal.

echo "#!/bin/bash" > hello.sh
echo "echo Hello Linux" >> hello.sh
chmod +x hello.sh
bash hello.sh

Build and execute a small script in the browser. For argument handling, traps, and full shell semantics, use the real Bash lab; the simulator implements only selected constructs.

Check your understanding

Explain the why.

Why should a filename expansion usually be written as "$file"?

Put it into practice.

Complete the exercises, then try the Boss Challenge without hints. Each quest checks its own objectives. You can revisit this chapter at any time.

Prefer to read first?

Make the learning stick.

Close the explanation and describe the main idea in your own words. Change a filename or input and predict the outcome. Tomorrow, repeat a quest without hints. Then apply it in a disposable real Linux environment.

Open the real-system labs →