🎓 A1Learner
🔍
0 of 46 lessons completed

Bash Intermediate Introduction

Bash Intermediate scripting is the practice of writing longer scripts that stay safe when something goes wrong. Longer scripts need structure, checks, and cleanup because one failure can spoil much more work.

A check before the main work

The script creates a data file, then checks that the file exists before reading it. The check line proves the gate passed before the work ran.

printf 'total: 42\n' > data.txt
if [ -f data.txt ]; then echo "data ready"; fi
cat data.txt

Functions keep steps separate

A function groups steps under one name. The main part of the script calls the function when that step is needed.

check_inputs() {
  echo "inputs checked"
}
check_inputs

Steps in order, one job each

The script lists its steps in order, and each step does one job. The output shows the same order as the steps.

echo "step 1: check inputs"
echo "step 2: process data"
echo "step 3: clean up"

Example

check_inputs() {
  echo "inputs checked"
}
printf 'report: ready\n' > report.txt
check_inputs
if [ -f report.txt ]; then echo "input checked"; fi
echo "step 1: read report"
cat report.txt
echo "step 2: work complete"

Key points

  • Structure: sections and small functions keep a long script easy to follow.
  • Checks: test inputs and files before the main work starts.
  • Cleanup: remove temporary files even when a step fails.
  • Fail fast: stop a script at the first serious error instead of piling on damage.
  • Growth cost: a mistake early in a long script can corrupt everything after it.
  • Honest limits: no check catches every mistake, so test scripts with real inputs.

In this example, a function named check_inputs prints one line when called. The script then writes a report file and calls the function. A file test confirms the report exists before the two work steps print.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Why does a longer script need checks and cleanup?