Shell scripting
The debugging chapter showed a tiny backup script. This chapter goes properly into bash scripting: how variables and quoting really work, how scripts make decisions and loop, and how to write scripts that stop loudly when something breaks instead of carrying on and doing damage.
Running a script
The first line, the shebang, tells Linux which program should run the file. #!/bin/bash points straight at bash; #!/usr/bin/env bash asks env to find bash in your PATH, which also works on systems where bash lives somewhere else (macOS with a newer bash, for example).
$ ./backup.sh # needs the execute bit and uses the shebang
bash: ./backup.sh: Permission denied
$ chmod +x backup.sh # fix: make it executable
$ ./backup.sh # runs in a new bash process
$ bash backup.sh # also works without +x (bash is the program, the file is its input)
$ source backup.sh # runs inside YOUR current shell (used for config files, not scripts)
The ./ is needed because the current folder is not in PATH. Avoid sh backup.sh on Ubuntu: sh is dash, a smaller shell that ignores the shebang and doesn't understand bash features like [[ ]], so you get errors such as [[: not found.
Variables and quoting
name="web-01" # no spaces around = (name = x runs a command called "name")
today=$(date +%F) # command substitution: 2026-09-27
count=$((3 + 4)) # arithmetic: 7
echo "Server $name on $today" # double quotes: variables ARE expanded
echo 'Server $name' # single quotes: printed literally -> Server $name
echo "${name}-backup.tar.gz" # braces mark where the name ends
echo "${ENVIRONMENT:-dev}" # use "dev" if ENVIRONMENT is unset or empty
: "${API_KEY:?API_KEY must be set}" # stop the script with this message if it's missing
Always put variables in double quotes. Unquoted, bash splits the value on spaces and expands wildcards, so a file called my notes.txt becomes two arguments:
file="my notes.txt"
rm $file # tries to delete "my" and "notes.txt"
rm "$file" # deletes the one file you meant
Arguments
| Variable | Meaning |
|---|---|
$0 | the script's own name, as it was called |
$1, $2… | the first, second… argument (${10} from ten on) |
$# | how many arguments were given |
"$@" | all arguments, each kept as a separate word. Use this form to pass them on or loop over them |
$? | exit code of the last command |
Exit codes, && and ||
Every command ends with an exit code: 0 means success, 1–255 mean some kind of failure, and each program documents its own codes. grep, for example, returns 0 if it found a match, 1 if it didn't and 2 on an error.
$ ls /nope
ls: cannot access '/nope': No such file or directory
$ echo $?
2
$ mkdir -p /tmp/build && cd /tmp/build # && runs the second only if the first succeeded
$ ping -c1 db-01 || echo "db-01 is down" # || runs the second only if the first failed
Your own script sets its exit code with exit 0 or exit 1. Cron, CI pipelines and monitoring tools look only at this number to decide whether your script worked.
&& and || only look at that one number. So do cron, CI pipelines and monitoring tools.Conditions: if, [ ] and [[ ]]
if runs a command and checks its exit code. [ ... ] (also called test) and bash's improved [[ ... ]] are just commands that succeed or fail. The spaces inside the brackets are required: [$x -gt 3] fails with [5: command not found.
if [[ -f /etc/nginx/nginx.conf ]]; then
echo "nginx config found"
elif [[ -d /etc/apache2 ]]; then
echo "looks like apache"
else
echo "no web server config" >&2
fi
if grep -q "ERROR" app.log; then # any command works as a condition
echo "errors in the log"
fi
if (( disk_used >= 90 )); then echo "disk almost full"; fi # (( )) for numbers
| Test | True when |
|---|---|
-f path / -d path / -e path | is a file / is a directory / exists at all |
-z "$s" / -n "$s" | string is empty / not empty |
"$a" == "$b", != | strings equal / different |
-eq -ne -lt -le -gt -ge | number comparisons (< inside [[ ]] compares text, not numbers) |
[[ $f == *.log ]] | pattern match (only in [[ ]]) |
! test, &&, || | not, and, or |
Loops
for host in web-01 web-02 db-01; do # over a list of words
ssh "$host" uptime
done
for f in /var/log/myapp/*.log; do # over files (quote "$f"!)
gzip "$f"
done
for i in {1..5}; do echo "attempt $i"; done
while IFS= read -r line; do # a file line by line
echo "host: $line"
done < hosts.txt
until curl -fs http://localhost:8080/health > /dev/null; do # retry until it works
sleep 2
done
IFS= read -r is the safe way to read lines: it keeps leading spaces and backslashes exactly as they are in the file.
Functions and reading input
greet() {
local who="$1" # local: the variable disappears when the function ends
echo "hello $who"
}
greet "Demee"
read -rp "Deploy to production? [y/N] " answer
if [[ "$answer" == "y" ]]; then echo "deploying..."; fi
read -rsp "Password: " pw; echo # -s hides what you type
Arguments inside a function are $1, $2… of that call, not of the script. A function's return sets its exit code (0–255); to hand back text, echo it and capture it with result=$(myfunc).
Strict mode: set -euo pipefail
By default bash ignores failures and keeps going. Put this line under the shebang of every serious script:
-e: exit as soon as a command fails (except insideifconditions and&&/||chains, where failure is expected).-u: using a variable that was never set is an error (unbound variable) instead of silently being empty. That stopsrm -rf "$DIR/"turning intorm -rf /because of a typo in the name.-o pipefail: a pipeline fails if any part fails, not just the last. Without it,false | truecounts as success.
trap cleanup EXIT runs a function called cleanup whenever the script ends, even after an error, which is the place to delete temp files.
A complete example: health check
#!/usr/bin/env bash
# healthcheck.sh - check free disk space and that some URLs answer
set -euo pipefail
THRESHOLD="${THRESHOLD:-90}" # override: THRESHOLD=80 ./healthcheck.sh ...
LOG_FILE="${LOG_FILE:-/tmp/healthcheck.log}"
failures=0
log() {
echo "$(date '+%F %T') $*" | tee -a "$LOG_FILE"
}
check_disk() {
local mount="$1" used
used=$(df --output=pcent "$mount" | tail -n 1 | tr -dc '0-9')
if (( used >= THRESHOLD )); then
log "FAIL disk $mount is ${used}% full"
return 1
fi
log "ok disk $mount is ${used}% full"
}
check_url() {
local url="$1" code=0
curl -fs -o /dev/null --max-time 5 "$url" || code=$?
if (( code != 0 )); then
log "FAIL $url (curl exit code $code)"
return 1
fi
log "ok $url"
}
if [[ $# -eq 0 ]]; then
echo "usage: $0 URL [URL...]" >&2
exit 2
fi
check_disk / || failures=$((failures + 1))
for url in "$@"; do
check_url "$url" || failures=$((failures + 1))
done
if (( failures > 0 )); then
log "$failures check(s) failed"
exit 1
fi
log "all checks passed"
$ chmod +x healthcheck.sh
$ ./healthcheck.sh http://localhost:8080/ http://localhost:9000/health
2026-09-27 10:15:02 ok disk / is 29% full
2026-09-27 10:15:02 ok http://localhost:8080/
2026-09-27 10:15:02 FAIL http://localhost:9000/health (curl exit code 7)
2026-09-27 10:15:02 1 check(s) failed
$ echo $?
1
curl -f makes HTTP errors (4xx/5xx) count as failures. Its exit code tells you why: 6 = couldn't resolve the host name, 7 = couldn't connect, 22 = the server answered with an HTTP error, 28 = timed out. The next chapter shows how to run this every few minutes with cron.
Common mistakes
name = valuegivesname: command not found. Remove the spaces around=.((count++))underset -ekills the script whencountis 0, because(( ))returns failure when the result is 0. Usecount=$((count + 1)).- A script written on Windows has CRLF line endings; bash then reports
cannot execute: required file not found(older versions:/bin/bash^M: bad interpreter). Fix withsed -i 's/\r$//' script.shordos2unix. - Unquoted
$varor$@break on spaces. Quote them. - Install
shellcheck(sudo apt install shellcheck) and runshellcheck script.sh: it catches most of these before you run anything.