Scripts
A file of commands, with a first line naming its interpreter
A script is a text file of commands; the shebang line names the interpreter and chmod +x makes it runnable.
A script is just a text file of commands, and the first line, hash bang, says which program should run it. Make it executable once, with chmod. Then run it by path, or hand it to bash directly; put it in user local bin and it runs from anywhere. When it ends, it leaves an exit status: zero for success.
Expansion
Before a line runs, bash fills in every $
Bash expands variables, command substitution and arithmetic before running a line; single quotes stop it.
Bash rewrites every line before running it. A variable is set with no spaces round the equals sign. Inside double quotes, dollar name becomes its value. Dollar brackets runs a command and puts its output in place. Double brackets do arithmetic. Braces add defaults, such as slash etc when no argument was given, and cut paths into pieces. Single quotes switch all of this off.
Arrays · Going deeper
A list of items, each kept whole
An array holds many values; "${files[@]}" gives each one intact, ${#files[@]} counts them.
Quoting
An unquoted variable splits at spaces; quotes keep it whole
Unquoted expansions undergo word splitting and globbing; "$var" always stays one argument.
This variable holds one file name, with a space in it. Without quotes, bash splits the value at the space, so rm receives two names, neither of them right. With double quotes, rm receives one name, the right one. printf shows the split plainly. The rule: quote every variable.
Exit codes and tests
if runs a command and acts on its exit status
Every command returns an exit status, 0 for success; if, && and || act on it, and and (( )) are the test commands.
Every command leaves a number behind: zero when it worked, something else when it did not. grep found root and returned zero; it did not find the other name and returned one. if runs a command and takes the then branch on zero. Double ampersand and double bar chain commands on success or failure. Double square brackets test files, strings and patterns; double round brackets compare numbers.
Loops
Repeat for each item, each line or each argument
for walks a list or glob, while read walks lines, case matches patterns; $1, $# and "$@" are the script’s arguments.
A for loop runs once for each item in a list, or each file a wildcard matches. while read runs once for each line of a file, kept exactly as written. case picks a branch by pattern, with a star for everything else. And the script’s own arguments arrive as dollar one, dollar two, and so on: dollar hash counts them, and dollar at in quotes passes them all on intact.
A real script
A backup script, line by line
Settings with defaults, safety settings, a log function, an input check and an array that keeps the newest seven archives.
Here is a complete, real script: it archives a directory and keeps the newest seven copies. The first line runs it with bash. Then the safety settings. The settings come next, each with a default: the first argument or slash etc, a variable or a standard path. A small function writes time-stamped messages to standard error. A trap reports the line if anything fails. The input is checked, with exit code two for wrong usage. Then tar makes the archive, and an array of existing archives, sorted by date, tells the loop how many old ones to remove.
Failing safely
Make the script stop at the first failure, and say where
set -e stops on errors, set -u on unset variables, pipefail on failures inside pipes; an ERR trap reports the line.
By default bash carries on after a command fails, which is how a backup script reports success with no backup. Three settings fix most of it: set dash e stops at a failure, set dash u stops at a misspelt variable, and pipefail makes a failure inside a pipeline count. A trap on error says where it happened. Here mkdir failed, the script stopped at line fourteen and exited with status one. set dash e has gaps, so check what matters yourself.
Failing safely · Going deeper · 1 of 2
bash -x shows every command as it really ran
bash -x prints each command after expansion, which shows exactly what values the script used.
Run the script with bash dash x, and it prints each command after expansion, marked with a plus. The missing argument became slash etc. The date ran first, inside the archive name. The path lost its leading slash for tar. There were eight archives and seven to keep, so one pass of the loop, which removes the oldest, then the test fails and the script logs that it is done.
ShellCheck · Going deeper · 2 of 2
Catch the classic bugs before the script runs
ShellCheck reads a script and names its bugs, such as unquoted variables and parsing ls, with a fix for each.
Scheduling
Five fields say when; cron runs it with no one watching
A crontab line has five time fields, minute, hour, day, month and weekday, then the command; give full paths and log the output.
A cron line starts with five fields: minute, hour, day of the month, month and day of the week. Thirty, two, star, star, star means half past two every morning. Put it in your own table with crontab dash e, or in a file in cron dot d, which adds a user field. Cron runs with a bare environment and no terminal, so use full paths and send the output to a log.
Lab
Write, break and schedule a backup script
Write the backup script by hand, check it with ShellCheck, trace it, break it, extend it, and schedule it with cron.
In this lab you write the backup script from these pages, check it, trace it and break it on purpose, then add a feature and let cron run it. Press the down arrow for the steps.
Lab · Going deeper
Write, break and schedule a backup script
Type the script from the annotated page rather than pasting it: you learn more from your own typos. Work as root, or with sudo, because it reads /etc.
Type the script from the annotated page rather than pasting it: you learn more from your own typos. Work as root, or with sudo, because it reads /etc. Steps. Warm up. At the prompt: name=you; echo "hi $name"; echo 'hi $name'; f="a b"; touch "$f"; ls -l $f; ls -l "$f". Explain each result. Write it. Create backup-etc with the lines from the annotated page; chmod +x; run shellcheck on it until it is clean. Run it. sudo ./backup-etc; ls -l /var/backups/etc; tar -tzf on the new archive | head. Trace it. Make eight empty fake archives with older dates (touch /var/backups/etc/etc-2026-01-0{1..8}-0000.tar.gz), then sudo bash -x ./backup-etc and follow the loop. Break it. Run it with a missing directory and print $?. Then BACKUP_DIR=/proc/x and read the trap message. Remove set -e and watch it carry on. Add a feature. Accept a second argument for how many copies to keep, with a default of 7, and reject anything that is not a number: $2 =~ ^[0-9]+$ . Install it. Copy it to /usr/local/bin and add /etc/cron.d/backup that runs it every two minutes, with output appended to /var/log/backup-etc.log. Watch it. tail -f /var/log/backup-etc.log for a few minutes; journalctl -u cron (crond on RHEL) shows each start. Finish. Change the schedule to 02:30 daily. Optional: replace cron with a systemd service and timer, as in lesson 8. Check: ls /var/backups/etc shows no more copies than you asked to keep, the log has a line from each run, and ./backup-etc /nope exits with status 2.
Steps
- Warm up. At the prompt: name=you; echo "hi $name"; echo 'hi $name'; f="a b"; touch "$f"; ls -l $f; ls -l "$f". Explain each result.
- Write it. Create backup-etc with the lines from the annotated page; chmod +x; run shellcheck on it until it is clean.
- Run it. sudo ./backup-etc; ls -l /var/backups/etc; tar -tzf on the new archive | head.
- Trace it. Make eight empty fake archives with older dates (touch /var/backups/etc/etc-2026-01-0{1..8}-0000.tar.gz), then sudo bash -x ./backup-etc and follow the loop.
- Break it. Run it with a missing directory and print $?. Then BACKUP_DIR=/proc/x and read the trap message. Remove set -e and watch it carry on.
- Add a feature. Accept a second argument for how many copies to keep, with a default of 7, and reject anything that is not a number: $2 =~ ^[0-9]+$ .
- Install it. Copy it to /usr/local/bin and add /etc/cron.d/backup that runs it every two minutes, with output appended to /var/log/backup-etc.log.
- Watch it. tail -f /var/log/backup-etc.log for a few minutes; journalctl -u cron (crond on RHEL) shows each start.
- Finish. Change the schedule to 02:30 daily. Optional: replace cron with a systemd service and timer, as in lesson 8.
Lesson complete
You finished “Shell scripts”
Nicely done.