Master

Writing shell you can hand over

Shell that only you can run is not automation. The next person has to read the script, and in six months you are that person. The bar is the same as for any code: state what it does, refuse to do anything surprising, and make each step checkable.

What you will see

The habit: a reviewer can read the plan without running it, which is the point of writing shell for handover.

About 2 min of reading

Try It

Write a dry run guard.

1

The guard

printf '#!/bin/sh\nrun=1\necho "PLAN: would remove *.tmp in ."\n[ "$run" = 1 ] || exit 0\n' > safe.sh && chmod +x safe.sh && ./safe.sh

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The plan printed - and the run flag is the single place that decides whether anything happens.
2

The habit it encodes

echo 'review the plan line, then set the flag'

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The habit: a reviewer can read the plan without running it, which is the point of writing shell for handover.

Data Flow

A plan is shown, then run, then cleaned.
1 State inputs and effects at the top
↓
2 Print the plan
↓
3 Run only with an explicit flag
↓
4 Clean up on exit
Why this works
One job per script, named by its file

A file called build.sh that builds one thing is reviewable on its own. A giant script with twelve modes has state that only makes sense in the middle, and that is the kind of script nobody can hand over.

Leave the tree cleaner than you left it

Clean up temporary folders on exit, including on failure. A script that leaves debris behind fails the next run, and a failure that is caused by leftover state is the kind that makes automation untrustworthy.

Examples

Say what it does at the top

A comment block naming the inputs, the outputs, and the side effects. A reader then knows before running whether the script writes files, and there is no surprise in the middle of a run.

Dry run by default

Print the commands instead of running them unless a flag is passed. A script that shows its plan by default can be reviewed by anyone, and the destructive mode is a deliberate choice.

Name the step that failed

When a step fails, print which step and what it was given. A script that exits with a number tells you nothing; one that names the step and the input tells you where to look.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Debugging a shell script
Previous Lesson
Debugging a shell script