Bash scripting for repeatable work

Learning objectives

Write a small Bash script that validates its input, quotes paths, reports useful errors, and returns clear exit statuses.

1 Objective→ 2 Learn→ 3 Example→ 4 Practice→ 5 Verify→ 6 Continue
How to study this lessonUnderstand the idea first. Use the example to see the behaviour, practise where provided, then make sure you can explain the result before continuing.

Explanation

Turn commands into a repeatable tool

A script stores a tested command sequence. The first line, called the shebang, selects the interpreter. Positional arguments such as $1 let the caller supply inputs. Variables make values reusable.

Essential syntax

Syntax Purpose Example
#!/usr/bin/env bash Select Bash. First line of the script.
"$1" Read the first argument without splitting spaces. input=$1 then cat -- "$input"
if ...; then Run commands only when a condition is true. if [[ -f "$input" ]]; then
for item in ... Repeat work for a list. for log in logs/*.log; do
function_name() { ...; } Group reusable commands. fail() { printf ...; }
exit number Return a result to the caller. exit 2
set -u Treat an unset variable as an error. set -u
set -o pipefail Report a failed command inside a pipeline. set -o pipefail

Quote variable expansions unless word splitting is intentional. set -e has exceptions and does not replace deliberate error handling.

Worked example

Save this as check-input.sh:

#!/usr/bin/env bash
set -u
set -o pipefail

if (( $# != 1 )); then
    printf 'usage: %s FILE\n' "$0" >&2
    exit 2
fi

input=$1
if [[ ! -f "$input" ]]; then
    printf 'missing file: %s\n' "$input" >&2
    exit 3
fi

printf 'sha256: '
sha256sum -- "$input"

Run and inspect it:

chmod u+x check-input.sh
./check-input.sh
printf 'missing-argument status=%s\n' "$?"
./check-input.sh "file with spaces.txt"
printf 'file-check status=%s\n' "$?"

Expected result: no argument returns status 2; a missing file returns status 3; an existing file produces its SHA-256 checksum and status 0.

RTL/DV use

A compile script should validate source paths, create a fresh output directory, capture compiler output, stop after compilation failure, run the simulation, and summarize the log.

Common mistakes

  • Writing $input instead of "$input".
  • Continuing to simulation after compilation failed.
  • Reusing old output without identifying it.
  • Logging credentials or the full private environment.
  • Running an unknown script because it is short.

Check yourself

What problem does quoting "$input" prevent?

Engineering practice

Practice: Bash scripting for repeatable work

Task→Run / reason→Check result→Explain why

Extend the script to accept an output directory and write the checksum there. Test a missing argument, a missing file, and a filename containing spaces.

Practice work is non-certified and is not stored by ASIC Campus.