Writing a small script
A script is a file of commands that runs like any other program: it takes arguments, reports success or failure, and stops cleanly when something goes wrong. The same habits make a pasted block of commands stop safely instead of closing your terminal.
A file of commands
In Reading and changing files you saved commands in a file and ran it with bash steps.sh. That file was already a script: bash reads it line by line and runs each line as if you had typed it. A script can also behave like a proper command: take arguments, say whether it worked and refuse bad input clearly.
The running example is Ava's list of photos, downloads.txt. Each line holds a photo's name, whether it is public or private, and how many times it has been downloaded:
harbor-at-dawn public 120
market-stalls private 45
lighthouse public 310Her first script, report.sh, has two lines:
# Show how many photos downloads.txt lists
wc -l < downloads.txtA line that starts with # is a comment, there only for the next person who reads the file. The .sh at the end of the name tells people the file is a shell script; bash does not care about it. bash report.sh prints 3.
Making it runnable
Typing bash before every script works, but a script can also run like any other command. That takes two changes. The first is a special opening line, called the shebang:
#!/usr/bin/env bash
# Show how many photos downloads.txt lists
wc -l < downloads.txtWhen a file starts with #!, the system reads the rest of that line as the program that should run the file. /usr/bin/env bash means "find bash on my PATH and use it". That matters on macOS, where /bin/bash is an old version 3 and the bash 5 you installed during setup comes first on your PATH. The shebang must be the very first line, with nothing before the #!.
The second change is permission. Every file records who may read it, write it and execute it, which means run it as a program. ls -l shows these as the ten characters at the start of the line:
$ ls -l report.sh
-rw-r--r-- 1 ava ava 62 Oct 5 10:12 report.sh
$ chmod +x report.sh
$ ls -l report.sh
-rwxr-xr-x 1 ava ava 62 Oct 5 10:12 report.shThe first character is - for an ordinary file or d for a directory. The other nine are three groups of three: what the file's owner may do, what members of the file's group may do, and what everyone else may do. In each group, r, w and x stand for read, write and execute, and - means not allowed. chmod +x, "change mode, add execute", added an x to all three groups. Without it, running the script answers Permission denied.
Now ./report.sh runs it. The ./ matters. When a command name contains no slash, the shell looks for it only in the directories listed in PATH, and the current directory, $PWD, is deliberately not on that list, so a file that happens to share a command's name cannot run by surprise. ./report.sh is a relative path to one exact file, so the shell runs that file.
Arguments and exit codes
Ava's script only works on downloads.txt. A script can take arguments the same way any command does. Inside it, $1 holds the first argument, $2 the second, and so on. $# holds how many there are, and $0 the name the script was run as. "$@" stands for all of the arguments, each kept whole as a separate word, which is the form to use when you pass them on to another command:
#!/usr/bin/env bash
# Show how many photos each file lists
echo "Checking $# files"
wc -l "$@"Run as ./report.sh downloads.txt "old downloads.txt", it prints Checking 2 files, and wc receives exactly two names, the second with its space intact. Without the quotes, $@ would be split at that space like any unquoted variable.
shift removes the first argument and moves the rest down, so $2 becomes $1, $# drops by one and "$@" no longer includes the old first argument. It lets a script take one argument for itself and hand everything else on.
Every command reports how it went through its exit code, the number echo $? showed in Terminals and shells: 0 for success, 1 to 255 for some kind of failure. A script's own exit code is the exit code of the last command it ran, unless it stops early with exit and a number. A good script checks its arguments before doing any work, explains a mistake on standard error, and stops with a code that says what went wrong:
if [[ $# -ne 1 ]]; then
echo "Usage: $0 FILE" >&2
exit 2
fiThe test is a [[ ]] test like the ones in Searching and shaping text, this time comparing numbers: -ne means "not equal", so [[ $# -ne 1 ]] is true whenever the script was given anything other than exactly one argument. >&2, from Connecting commands with pipes and redirection, keeps the message out of the script's real output, so a pipe or $( ) that collects that output never receives it. Exiting with 2 for a wrong command line is a common convention; grep follows it too.
Making decisions
Searching and shaping text used if with a [[ ]] test that compares text. if accepts any command, not only a test: it runs the command, and when its exit code is 0 it runs the lines after then, otherwise the lines after else, if there are any:
if grep -q lighthouse downloads.txt; then
echo "The lighthouse photo is listed"
else
echo "No lighthouse photo"
figrep -q prints nothing and answers only through its exit code: 0 for a match, 1 for none, 2 when it could not read the file. [[ ]] has more tests than comparing text:
| Test | True when |
|---|---|
[[ $count -gt 10 ]] | The number is greater than 10. The other number tests are -eq (equal), -ne (not equal), -lt (less than), -le (less than or equal) and -ge (greater than or equal) |
[[ -f "$file" ]] | The path exists and is a regular file (-d for a directory) |
[[ -z "$value" ]] | The text is empty (-n for not empty) |
[[ ! -f "$file" ]] | ! turns any test around: here, the file does not exist |
Numbers need the letter operators: inside [[ ]], > compares text in dictionary order, which puts "9" after "10". Other people's scripts often use an older form with single brackets, [ "$a" = "$b" ], which takes the same tests. There, [ is an ordinary command whose arguments are split like any other, so every variable inside needs double quotes or an empty one disappears and the test breaks.
When one value can take several forms, case reads more clearly than a row of if tests. It compares the value with each pattern in turn and runs the lines of the first that matches, up to ;;:
case "$1" in
public|private) echo "Listing $1 photos" ;;
*) echo "Usage: $0 public|private" >&2; exit 2 ;;
esac| separates patterns that share the same lines, and *, which matches anything, catches every other value. esac, "case" backwards, ends the block.
Functions
A function gives a name to a group of commands, so you can run them wherever you need them. You define it with the name, () and the commands in braces, and call it like a command. Inside it, $1, $# and "$@" refer to the function's own arguments, not the script's:
count_in() {
local pattern="$1"
shift
grep -c "$pattern" "$@"
}
count_in lighthouse downloads.txt old-downloads.txtcount_in keeps its first argument as the pattern, removes it with shift, and hands every remaining argument to grep unchanged, so grep prints a count for each file. local keeps pattern inside the function, so it cannot overwrite a variable with the same name elsewhere. A function defined at the prompt lasts until the shell ends, and a file of functions loaded with source defines them in your current shell, just as it did for variables in Variables, quoting and the environment.
A function hands back results in two ways. What it prints is its output, which $( ) can capture. Its exit code is the exit code of its last command, or the number given to return, which ends the function early. return leaves only the function; exit ends the whole shell that is running it. That makes || return 1 the way to stop a function at a failed step:
public_total() {
[[ -f "$1" ]] || { echo "No such file: $1" >&2; return 1; }
local total=0 photo visibility downloads
while read -r photo visibility downloads; do
if [[ "$visibility" == "public" ]]; then
total=$((total + downloads))
fi
done < "$1"
echo "$total"
}The braces after || group two commands, so a missing file both prints a message and returns 1. With Ava's file, public_total downloads.txt prints 430: 120 for the harbor and 310 for the lighthouse, with the private market photo skipped.
Stopping a pasted block safely
A script runs in a child shell, so its exit ends only that child. A block of lines you paste into your terminal runs in your own interactive shell, and there exit ends the shell itself: the terminal closes, and every variable you exported is gone. Pasted lines also run one after another whatever happens, so a failed line does not stop the lines after it, and || return 1 outside a function only prints an error.
Three shapes make a pasted block stop at a failure without closing anything. The labs from here on use them. When one check guards everything after it, make the block one if:
if cd ~/btl-course; then
ls
else
echo 'Could not enter the course folder. Fix the error above, then run this block again.'
fiWhen several checks come in a row, put the steps in a function with || return 1 at each check, and call it on the block's last line, saying what happened when it stops:
check_downloads() {
cd ~/btl-course || return 1
[[ -f downloads.txt ]] || { echo 'downloads.txt is missing.'; return 1; }
public_total downloads.txt
}
check_downloads || echo 'Stopped at the failed check above. Nothing after it ran.'When the check is the block's last command, there is nothing left to stop, so print what went wrong and keep the failing status: public_total downloads.txt || { echo 'Could not total the downloads.'; false; }. false is a command that does nothing and fails.
One shortcut looks like an if and is not. In A && B || C, C runs when A fails, and also when A succeeds but B fails. [[ -f downloads.txt ]] && public_total downloads.txt || echo 'No downloads file' would claim the file is missing if the total failed for another reason. Use if ...; then ...; else ...; fi when you mean one or the other.
Safety settings
Here is Ava's whole script, built from the pieces above, with one more line near the top:
#!/usr/bin/env bash
# Print the total downloads of the public or private photos listed in a file.
set -euo pipefail
usage() {
echo "Usage: $0 public|private FILE" >&2
exit 2
}
total_for() {
local wanted="$1" file="$2" total=0 photo visibility downloads
while read -r photo visibility downloads; do
if [[ "$visibility" == "$wanted" ]]; then
total=$((total + downloads))
fi
done < "$file"
echo "$total"
}
if [[ $# -ne 2 ]]; then
usage
fi
case "$1" in
public|private) ;;
*) usage ;;
esac
if [[ ! -f "$2" ]]; then
echo "No such file: $2" >&2
exit 1
fi
total_for "$1" "$2"set -euo pipefail turns on three settings that make a script stop at the first sign of trouble instead of carrying on with a half-finished result:
-estops the script as soon as a command fails.-utreats a variable that was never set as an error. A typo such as$totlwould otherwise quietly become empty text.-o pipefailmakes a pipeline fail when any command in it fails. Without it, a pipeline reports only its last command's exit code, as Connecting commands with pipes and redirection showed.
-u is why the argument check comes first. Without an argument, $1 was never set, and bash would stop with a terse unbound variable error. The check stops first with a clear message and the usual exit code:
$ ./total-downloads.sh public downloads.txt
430
$ ./total-downloads.sh
Usage: ./total-downloads.sh public|private FILE
$ echo $?
2-e deliberately ignores commands whose exit code is being tested, such as the condition of an if or the left side of && and ||, which is why if grep -q ... still works. A bare command that fails still stops the script, and that includes commands that fail on purpose. count=$(grep -c volcano downloads.txt) stops the script when there are no matches, because grep prints 0 and exits with 1. Writing count=$(grep -c volcano downloads.txt || true) keeps the count and the script; true is the command that does nothing and succeeds.
These settings belong in scripts, never at your prompt. Typed into your interactive shell, set -e closes the terminal at the first command that fails.
A scratch folder that cleans up
Scripts that create files of their own often work in a fresh, empty folder, so two runs never trip over each other's files. mktemp -d creates a folder with a random, unused name and prints its path, ready to keep in a variable. trap names commands for the shell to run when something happens, and EXIT means "when this shell ends", however it ends:
#!/usr/bin/env bash
set -euo pipefail
workdir=$(mktemp -d "$PWD/report.XXXXXX")
trap 'rm -r "$workdir"' EXIT
cd "$workdir"
echo "Working in $workdir"mktemp replaces the run of Xs with random characters, giving a name such as report.k3T9qa in the current directory. The trap's command is in single quotes, so $workdir is expanded when the trap runs, not when it is set. Whether the script finishes, stops at a usage check or is stopped by set -e, the folder is removed on the way out.
A pasted block has no such moment: your interactive shell ends only when you close the terminal. So a lab creates its folder the same way inside an if guard, if LAB_DIR=$(mktemp -d "$PWD/btl-lab.XXXXXX") && cd "$LAB_DIR"; then ..., and removes it in its Cleanup with rm -r "$LAB_DIR".
Check your understanding
Try these questions before moving on. If an answer isn't right, use the feedback and try again.
Try it in the Lab
- Write a script that adds up your shipped ordersWrite and run scripts with arguments, exit codes, case and safety settings, build the labnet helper you will use in later labs, and send the total of your shipped orders from a block that stops safely.