At eleven at night you deploy notes-api. The script finishes without a complaint, and you go to bed. Next morning people using the app still find the bug that was supposedly fixed: the server is still running yesterday's code, and the script gave no warning.
A shell script is a file of commands that bash (the most common shell on Linux) runs line by line, exactly as if you typed them one by one. On a server, the most important script is the deploy script, which installs a new version of the app. Its steps: fetch the new code, install the dependencies (the npm packages the app uses), run the database migrations (changes to the tables), then restart the app. Picture a pilot's pre-flight checklist: if one check fails, the plane does not take off. Each deploy step is one check on that checklist. A good deploy script stops as soon as one step fails, and says that the deploy failed. The basics (shebang, variables, if, $?) are in the Shell Script Basics lesson of the Terminal track.
deploy.sh for notes-api
This is the deploy script of notes-api:
#!/bin/bash
set -euo pipefail
APP_DIR="/srv/notes-api"
BRANCH="${1:-main}"
echo "Deploying notes-api from branch $BRANCH"
cd "$APP_DIR"
git pull --ff-only origin "$BRANCH"
npm ci --omit=dev
node migrate.js | tee -a deploy.log
sudo systemctl restart notes-api
echo "Deploy complete!"
#!/bin/bash(the shebang) tells the system that bash runs this file. On Ubuntu,/bin/bashand/usr/bin/bashare the same file.#!/usr/bin/env bashlooks bash up inPATH, useful on machines that keep bash somewhere else.set -euo pipefail: three safeguards, covered below.APP_DIR="/srv/notes-api": a variable (a name that holds a value) is written with no spaces around=."${1:-main}"takes the first argument, ormainwhen it is empty. So./deploy.sh feature-logindeploys thefeature-loginbranch (a line of work in git).git pull --ff-only:git pullfetches the new code, and--ff-onlymakes git only move straight ahead: it adds new changes on top of the code that is there. If the code on the server was ever changed by hand, git refuses instead of quietly making a merge (a mix of two versions of the code).npm ci --omit=devinstalls the dependencies exactly aspackage-lock.json(the list of each package's version) says, without devDependencies (packages used only while developing).tee -a deploy.logshows the migration's output on screen and also adds it to the end ofdeploy.log.sudo systemctl restart notes-api(the previous lesson) stops the app's old process, then starts the app again with the new code.
Once only: chmod u+x deploy.sh (the File System & Permissions lesson), then run it with ./deploy.sh.
Exit codes: 0 is success, anything else is failure
Every command finishes with an exit code: 0 means success, any other number means failure. git uses 128 for a fatal error (an error that makes git stop). echo $? prints the last command's exit code. This is the same deploy.sh, without the set line, when GitHub cannot be reached. Before you read the output, guess: what is the last line printed, and what does echo $? print?
deploy@web-1:/srv/notes-api$ ./deploy.sh
Deploying notes-api from branch main
ssh: connect to host github.com port 22: Connection timed out
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
added 64 packages, and audited 65 packages in 3s
found 0 vulnerabilities
No new migrations.
Deploy complete!
deploy@web-1:/srv/notes-api$ echo $?
0
git pull failed with exit 128, but bash still moved on to the next line. npm ci reinstalled the old code's dependencies, and the app was restarted on the old code. Then the script printed Deploy complete! and exited with 0, because a script's exit code is the exit code of its last command, the echo. That is what happened that night, and CI (a server that runs the deploy automatically) or a teammate reading the exit code would think the deploy worked.
set -euo pipefail: three safeguards
With set -euo pipefail on the second line, the same event stops right there:
deploy@web-1:/srv/notes-api$ ./deploy.sh
Deploying notes-api from branch main
ssh: connect to host github.com port 22: Connection timed out
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
deploy@web-1:/srv/notes-api$ echo $?
128
This table shows what each safeguard catches. The line numbers are those of deploy.sh above:
| Safeguard | What it catches in deploy.sh | Without it |
|---|---|---|
-e |
git pull fails: the script stops at line 9, exit 128 |
it goes on to Deploy complete! |
-u |
the typo $BRANH: ./deploy.sh: line 7: BRANH: unbound variable, exit 1 |
$BRANH silently becomes empty text |
-o pipefail |
node migrate.js fails inside a pipe: it stops at line 11, exit 1 |
the pipe counts as a success because tee succeeded |
- A pipe's (
|) exit code is the exit code of its last command. Withoutpipefail,node migrate.js | tee -a deploy.logcounts as a success even when the migration failed, andset -ehas no reason to stop. -edoes not apply inside anifcondition or on the left of&&or||, because a failure there is being checked on purpose. (a && brunsbonly whenasucceeds,a || bonly whenafails.) The details, plustrapfor cleaning up when the script stops, are in the Defensive Scripting & trap lesson.
Quote every variable
Without quotes, bash splits a variable's value at spaces before it runs the command. In this example, touch makes an empty file:
LOG="storage/logs/deploy 2026-10-09.log"
touch $LOG # two files: "storage/logs/deploy" and "2026-10-09.log"
touch "$LOG" # one file, with exactly that name
Make it a habit to write "$APP_DIR", "$BRANCH", "$file". Double quotes still replace a variable with its value, single quotes ('$APP_DIR') do not: you get the text $APP_DIR as it is.
Loops: wait until the app is ready
After a restart, the app needs a few seconds before it is ready. The loop below checks it up to five times. for runs its body (the part between do and done) once for each item, here the numbers 1 to 5:
for i in 1 2 3 4 5; do
if curl -fsS http://127.0.0.1:3000/health > /dev/null; then
echo "Health check OK"
exit 0
fi
sleep 2
done
echo "Health check failed after 5 tries" >&2
exit 1
curlsends a request to the app's/healthaddress, which is used to check the app's health.curl -fexits with an exit code other than 0 when the server answers 4xx or 5xx (error status codes), soifcan use it directly.-sShides the progress display but still prints errors, and> /dev/nullthrows away the server's answer.- When the app is healthy,
exit 0ends the script with exit code 0 (success). When it is not yet,sleep 2waits 2 seconds before it tries again. - A loop's items can also be a list of files:
for file in /var/log/*.log; do echo "$file"; doneruns once for each.logfile. - The
exit 1at the end makes the script fail clearly if the app never got healthy.>&2prints the message as an error.
A deploy script from an array of lines
In the exercise, generateDeployScript(config) builds the script's text from an array of lines joined with "\n": the shebang #!/bin/bash, set -euo pipefail, one echo with the app name and branch, every step from config.steps (use the spread ...config.steps, which inserts everything in the array), then echo "Deploy complete!".
⚠️ When a deploy script lies, or stops for no reason
- No
set -e. The script goes on after a failed step and still printsDeploy complete!with exit 0. - A pipe swallows the error.
command | tee filealways succeeds whenteedoes. Addset -o pipefail. - Unquoted variables. A path with a space splits into two arguments, and an empty variable vanishes from the command.
sudoasking for a password mid-script. A script running with no terminal (from CI, for example) fails there. Allow just that one command without a password (NOPASSWD): open the sudo rules file withsudo visudo -f /etc/sudoers.d/deploy, then writedeploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart notes-api.- A
grepwith no match underset -e.grepexits with 1 when nothing matches, and the script stops. When "not found" is fine, writegrep ... || true, so that line always succeeds.
TL;DR: A deploy script (a file of commands that installs a new version of the app) starts with the shebang #!/bin/bash (or #!/usr/bin/env bash), the line that picks bash to run it. The next line is set -euo pipefail: -e stops at the first failed command, -u refuses variables that were never set, -o pipefail makes a pipe (|) fail when any of its parts fails. Exit code 0 means success, anything else failure, and echo $? shows it. Without -e, a failed script still exits with 0 from its last echo. Variables are written NAME="value" with no spaces and read as "$NAME" in quotes, and "${1:-main}" gives the first argument the fallback value main. for x in ...; do ...; done repeats for each item. sudo in a script needs a NOPASSWD (no password) rule for that one command.
⚡ The first two lines
Write:
#!/bin/bash
set -euo pipefail
Meaning: The shebang (the first line, starting with #!) tells the system that bash runs this file. set -euo pipefail adds three safeguards, so the script stops as soon as something goes wrong.
⚡ Exit codes: 0 means success
Write:
deploy@web-1:/srv/notes-api$ echo $?
0
Guess first: a deploy script runs git pull (fetch the new code), a few other commands, then echo "Deploy complete!". Without the set line, git pull fails with exit code (the number a command ends with) 128. What is the script's exit code?
0. Bash moves on to the next line, prints Deploy complete!, and a script's exit code is the exit code of its last command, the echo.
Meaning: 0 means success, any other number means failure, and echo $? prints it. With -e, the script stops at the first failed command, here git pull, and exits with its exit code: 128.
⚡ A pipe can swallow the error
Write:
node migrate.js | tee -a deploy.log
Meaning: The pipe (|) sends the database migration's output to tee, which writes it on screen and into deploy.log. A pipe's exit code is the exit code of its last command. Without pipefail, a failed migration still counts as a success because tee succeeded. -u refuses variables that were never set, like $BRANH, a typo of the variable $BRANCH.
⚡ Quote every variable
Write:
LOG="storage/logs/deploy 2026-10-09.log"
touch "$LOG"
Meaning: touch makes an empty file. Without quotes, touch $LOG makes two files, because bash splits the value at the space. With "$LOG", you get one file with exactly that name.