The Plain Picture#
Instead of texting the assistant the same ten instructions every morning, you write them on one sheet of paper and hand it over: "Do this list."
The Real Name#
A shell script is a text file of shell commands, run top to bottom as a program.
Under the Hood — a real deploy script#
#!/usr/bin/env bash
# deploy.sh — pull the latest code, install dependencies, restart StudyBuddy
set -euo pipefail
APP_DIR="/opt/studybuddy"
SERVICE="studybuddy"
echo "Deploying to ${APP_DIR}..."
cd "${APP_DIR}"
git pull --ff-only
./venv/bin/pip install -r requirements.txt
if sudo systemctl restart "${SERVICE}"; then
echo "Restarted ${SERVICE}"
else
echo "Restart failed" >&2
exit 1
fi
for i in 1 2 3 4 5; do
if curl -fsS http://localhost:8000/health > /dev/null; then
echo "Healthy after ${i} check(s)"
exit 0
fi
sleep 2
done
echo "App did not become healthy" >&2
exit 1Run it with chmod +x deploy.sh (Ch 4) and then ./deploy.sh.
Line by line, the parts that matter:
| Piece | Meaning |
|---|---|
#!/usr/bin/env bash | the shebang: which program should run this file (bash, found via PATH) |
set -e | stop at the first command that fails, instead of carrying on blindly |
set -u | treat using an unset variable as an error (prevents the rm -rf $EMPTY/ disaster, Ch 3) |
set -o pipefail | a pipeline fails if any stage fails, not just the last (Ch 5) |
APP_DIR="..." | a variable — no spaces around = |
"${APP_DIR}" | using it — always in double quotes, so values with spaces don't split into several arguments |
if cmd; then ... fi | branches on the command's exit code |
for i in ...; do ... done | a loop |
>&2 | write the message to stderr |
exit 1 | finish with a failure code, so CI pipelines (CI/CD (coming soon)) notice |
Quotes: double quotes "..." allow variables inside ("Hello $USER"); single quotes '...' are completely literal
('$USER' stays as those five characters).
Gotchas
Always start scripts with
set -euo pipefail. Without it, a failedcdis ignored and the following commands run in the wrong directory.Shell scripts get hard to maintain quickly. Past ~100 lines, or once you need real data structures, write it in Python instead.
Check yourself
4 questionsWhat does the shebang line do?
Show answerHide answer
Tells the system which interpreter should run the script.
What do set -e, set -u and set -o pipefail each prevent?
Show answerHide answer
-e: continuing after a failed command. -u: silently using unset variables. pipefail: hiding failures in earlier
pipeline stages.
Why quote "${VAR}"?
Show answerHide answer
So values with spaces or special characters stay one argument.
Single vs double quotes?
Show answerHide answer
Double quotes expand variables; single quotes keep everything literal.