Bash Scripting — Commands With Safety Switches
Deploying notes-api takes five commands: pull the code, install dependencies, run the tests, restart the service, check it answers. Typed by hand, one typo or one skipped failure ships a broken release. Saved as a Bash script, it runs the same way every time and stops the moment something goes wrong.
The rule
A script is your typed commands, saved, with the safety switches on.
A Bash script is a text file of the same commands you would type. Three things turn it from a list into a safe tool:
#!/usr/bin/env bash
set -euo pipefail
APP_DIR="/srv/notes-api"
cd "$APP_DIR"
git pull --ff-only
./.venv/bin/pip install -r requirements.txt
./.venv/bin/pytest -q
sudo systemctl restart notes-api
curl --fail --silent https://notes.example.com/health
echo "deploy finished"- The shebang
#!/usr/bin/env bashon line one says which interpreter runs the file. set -euo pipefailswitches on safety:-estops at the first failing command,-utreats an unset variable as an error, andpipefailmakes a pipeline fail if any stage fails, not only the last one.- Quoted variables.
"$APP_DIR"keeps a path with spaces as one argument.
Every command returns an exit code: 0 means success, anything else means failure. set -e reads these codes for you, and $? holds the last one if you want to check it yourself. Make the file executable once with chmod +x deploy.sh, then run it as ./deploy.sh.
The shortcut
Before you trust a script, run the three-switch check: shebang on line one, set -euo pipefail on line two, and every $VARIABLE wrapped in double quotes. Most beginner script disasters come from missing one of the three.
Pull and install
git pullandpip installsucceed, each returning exit code 0.
Without set -e, Bash would ignore the failure, restart the service with broken code and happily print "deploy finished".
Drills
Answer fast — trust the rule.
What exit code means a command succeeded?
What does set -e do in a Bash script?
FILE="my notes.txt", then rm $FILE. What goes wrong?
You created deploy.sh, and ./deploy.sh says "Permission denied". What is the fix?
Remember
- A script is your typed commands, saved, with the safety switches on.
- Shortcut: shebang,
set -euo pipefail, quoted variables. - Trap: a script that ignores a failure and carries on as if everything worked.
