Loading

T6 Linux and Bash · Lesson 8

Bash scripts

Writing commands down so that the machine can run them for you: a first script with its shebang, arguments, decisions with if and case, loops over lists, files and lines, functions, and the settings and traps that make a script stop safely at its first mistake.

  • write a script with a shebang, make it runnable, and run it
  • read arguments with $1, $# and "$@", and stop with a usage message
  • make decisions with if, test and case
  • repeat work with for and while loops, and read a file line by line
  • write functions with local variables and exit statuses
  • make scripts stop at the first error with set -euo pipefail, and clean up with trap
About 60 minutesChecked against GNU Bash on the laptop (the kit compares every shell block with it, in a sandbox) 5.3.9 (2026-11-07); GNU coreutils on the laptop (installed beside Ubuntu 26.04's default uutils; the kit's sandbox uses GNU's) 9.7 (2026-11-07)Play this lesson's games

The back cover

A script is a list of commands written down once, so that the machine can run them for you, as often as you like and even while you sleep. A nightly backup, a daily report and a check of every pump can each be one script.

These pages show a first script with its shebang, and how it reads its arguments. They show decisions with if and case, and loops over lists, files and lines. They show functions, and the settings that make a script stop safely when something goes wrong.

Before you start

The story: Forty words at midnight

Every night a watchman walks the Underway and speaks the same forty commands, in order, into the tubes: check the pumps, copy the day's log, clear the old ones, report. Last night he was tired, and said the seventeenth before the sixteenth.

The day's log was cleared before it was copied, and the day's records are gone.

Warden Rao puts a blank sheet in front of you. "A tired man does not need to be more careful," she says. "He needs to not be there. Write the forty words down. Then the tunnels can read them for themselves."

Everything in this step so far, you typed. A script is the same commands written in a file, so that the machine can run them in order, every time, without a tired watchman. This last lesson of the step joins all the earlier ones together: files, pipes, permissions, processes and variables all appear in scripts.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
Commands in order.mkdir a; cd aA script is a list of them.
The x right.chmod +x pump.shEvery script needs it to run by name.
Running by path../pump.shHow you start a script.
Variables."$name"Scripts are full of them.
The exit status.echo $?if decides by it.
&& and ||.mkdir x || echo failedif is the longer form.
Patterns.*.logfor loops run over them.
Redirection.> file 2>&1Scripts write reports.
Feeding a file in.wc -l < fileIts answer, kept in a variable.
Signals and statuses.143, 130trap runs code when a script ends.

By the end of this lesson you will be able to:

  • write a script with a shebang, make it runnable, and run it;
  • read arguments with $1, $# and "$@", and stop with a usage message;
  • make decisions with if, test and case;
  • repeat work with for and while loops, and read a file line by line;
  • write functions with local variables and exit statuses;
  • make scripts stop at the first error with set -euo pipefail, and clean up with trap.

How to follow this lesson

Each script appears twice on the page: once as the file, as you would write it in an editor, and then in a block that runs it. A hidden setup line writes exactly that file before the block runs, and makes it runnable. To try your own changes, press Edit on a running block and put commands straight in, or write a file with cat and a here document, as the last section shows.

In one line

A script is commands written in a file, so that the machine runs them the same way every time; this lesson shows how to write scripts that are clear, take arguments, decide, repeat, and stop safely.

Your first script

At a glance

A script is a plain text file of commands, one after another, as you would type them. Its first line, the shebang, says which program should run it.

Write #!/bin/bash at the very top, make the file runnable with chmod +x, and run it by its path, as ./round.sh. Lines that start with # are comments, for people, and bash skips them. When a line fails, the error names the script and the line number. By default the script then carries on with the next line.

Take a guess: Who added the #! line to Unix, and when?

A script is a plain text file of commands, one after another, as you would type them. Here is the watchman's round, cut down to two lines of work:

round.sh

#!/bin/bash
# the nightly round
echo "checking pumps"
echo "round done"

Look at each kind of line. The first line, which starts with #!, is the shebang. Lines that start with # are comments, for people. The rest are ordinary commands.

Shebang

The first line of a script, starting with #! and then the path of the program that should read the file, such as #!/bin/bash. When you run the file by its path, the kernel reads this line and starts that program.

To run the script by its path, it needs the x right, from the permissions lesson. Then it runs like any program:

With round.sh, shown above, made runnable

./round.sh
echo $?
bash round.sh
checking pumps
round done
0
checking pumps
round done

The status of a script is the status of the last command it ran, here 0. The second way, bash round.sh, hands the file to bash to read, and works even without the x right or the shebang. Running it by its path is better for a finished script, because the shebang then makes sure that bash reads it, whichever shell you are typing in.

Errors name the script and the line

When a command in a script fails, the message starts with the script's name and the line number, which tells you where to look. Unless you say otherwise, the script then carries on to the next line:

With broken.sh: echo one, a mistyped command on line 3, then echo two

./broken.sh
echo $?
one
./broken.sh: line 3: nosuchcommand: command not found
two
0

It carried on, and even ended with 0, because its last command worked. The last section shows how to make a script stop at its first mistake instead.

StepHowWhy
write ita text editor, or cat with a here documenta plain text file
first line#!/bin/bashsays which program reads it
make it runnablechmod +x round.shthe x right, once
run it./round.shby its path, or by name if its folder is in PATH
check itecho $?the last command's status

Worked example 1

Write the watchman's round as a script without an editor, from the prompt: a shebang, a comment, and two echo lines. Make it runnable, and run it.

What we have: the commands of the round, and a shell prompt

What we need: a runnable round.sh that prints its two lines

The plan: cat with a here document writes several lines into a file: everything up to the end word goes in. Then chmod +x and run it by its path

cat > round.sh <<'END'
#!/bin/bash
# the nightly round
echo "checking pumps"
echo "round done"
END
chmod +x round.sh
./round.sh
checking pumps
round done
  1. The quotes round END keep the shell from changing anything inside, such as a $, while it writes the file. The file now holds exactly the four lines between the two END lines.

round.sh prints checking pumps and round done.

Check: running cat round.sh would show the four lines, shebang first.

A path that fails: leaving out chmod +x. Then ./round.sh says Permission denied, with status 126, as the permissions lesson showed.

When you are stuck: a script will not run, or runs strangely

Permission denied: chmod +x script.sh.

command not found: run it as ./script.sh, with the path.

An error names a line: open the file and read that line.

The shebang must be the very first line, with no space before #!.

Your turn

What does the first line #!/bin/bash do?Tap to reveal
  1. It is read when the file is run by its path.
  2. It names the program that reads the file.

It says that /bin/bash should run the file.

A script's middle command fails, and its last command works. What is the script's exit status?Tap to reveal
  1. A script's status is its last command's.

0, unless the script is told to stop on errors.

./round.sh | wc -l
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
2
  1. round.sh prints two lines.
  2. wc -l counts them.

It prints 2.

Did you know?

#! since January 1980

The #! line is younger than Unix. In a mail dated 10 January 1980, Dennis Ritchie announced that if a file being run begins with the magic characters #!, the rest of the line names the interpreter for it. The mail listed the gains: scripts become more like real programs, and ps shows a script's real name instead of sh. It seems the mark had no name at first.

Why it fits here: It answers this topic's question: Dennis Ritchie added the #! line to Unix in January 1980.

Sources: Wikipedia: Shebang (Unix); Sven Mascheck: The #! magic, details about the shebang mechanism

The word shell, from 1964

The word shell was coined for this kind of program. Louis Pouzin, then on the computer centre staff at MIT, recalls writing a paper on how the command language of Multics could be designed. Pouzin coined the word shell to name it, at the end of 1964 or the start of 1965. Glenda Schroeder of MIT and an engineer from GE later wrote the first Multics shell.

Why it fits here: It names the program this topic's scripts run in: the word shell was coined by Louis Pouzin around the end of 1964.

Source: Louis Pouzin: The Origin of the Shell

In one line

A script is a text file of commands, with a shebang such as #!/bin/bash as its first line. Make it runnable with chmod +x and run it as ./name. Errors name the script and the line, and by default the script carries on.

Arguments: $1, $# and "$@"

At a glance

A script that can be told what to work on is far more useful than one that always does the same thing. Words written after a script's name are its arguments.

Inside, $1 is the first argument, $2 the second, and so on; $# counts them and $0 is the script's own name. Written in double quotes, "$@" is every argument, each kept whole. The command shift moves them all down by one. A careful script checks its arguments first, and when they are wrong, it prints a usage line to standard error and exits with 2.

Take a guess: Why does $10 not give the tenth argument?

A script that does the same thing every time is useful; one that can be told what to work on is far more useful. Words written after a script's name are its arguments, just as they are for any command, and the script reads them through special names:

args.sh

#!/bin/bash
echo "script: $0"
echo "first: $1"
echo "second: $2"
echo "count: $#"
echo "all: $@"

With args.sh, shown above

./args.sh north "east gate"
./args.sh
script: ./args.sh
first: north
second: east gate
count: 2
all: north east gate
script: ./args.sh
first: 
second: 
count: 0
all: 
NameHoldsHere
$0the script's own name, as it was run./args.sh
$1, $2, ...each argument, in ordernorth, east gate
$#how many arguments there are2
"$@"every argument, each kept wholenorth, then east gate

The quotes in the call mattered: "east gate" arrived as one argument, $2. An argument that is missing is empty, with no error, as the second run shows.

Always "$@", in quotes

To go through every argument, use "$@" with its double quotes. Each argument then stays whole, spaces and all. Without the quotes, the arguments are split at their spaces, exactly as an unquoted variable is:

With each.sh, which loops over "$@" and then over $@

./each.sh one "two words"
[one]
[two words]
---
[one]
[two]
[words]

shift, and defaults

shift drops $1 and moves every other argument down one place, which is handy when the first argument is special. And the default trick from the last lesson works on arguments too: ${1:-north} is the first argument, or north when there is none.

With s.sh, which prints $1, shifts, then prints $1 and $#; and d.sh, which uses ${1:-north}

./s.sh a b c
./d.sh
./d.sh east
a
b 2
station north
station east

Saying how to use it

A good script checks its arguments first, and when they are wrong, says how to use it and stops. The message goes to standard error with >&2, and the script ends with a status other than 0, by custom 2 for a wrong use:

station.sh

#!/bin/bash
# report on one station, named as the first argument
if [ $# -ne 1 ]; then
  echo "usage: $0 station" >&2
  exit 2
fi
echo "station $1: all pumps running"

The command exit ends the script at once, with the status you give it.

Reading an answer: read

A script can also ask for input with read, which reads one line into a variable. On this page there is no keyboard, so the line arrives through a pipe:

With ask.sh: read -r name, then echo Hello, $name

echo Asha | ./ask.sh
Hello, Asha

The -r keeps backslashes in the line as they are, and is a good habit. Arguments are usually the better choice, as a script that asks questions cannot run by itself at midnight.

Worked example 2

The warden wants station.sh, shown above, to report on any one station, and to refuse politely when it is given none, or too many. Run it three ways, and check each status.

What we have: station.sh, which checks $# first

What we need: the report for north, and the usage message, with status 2, for no station and for two

The plan: $# counts the arguments; when it is not 1, the script prints the usage line to standard error and exits with 2

With station.sh, shown above

./station.sh
echo $?
./station.sh north
./station.sh north south
echo $?
usage: ./station.sh station
2
station north: all pumps running
usage: ./station.sh station
2
  1. $0 in the usage line printed the name the script was run by, so the message stays right even if the file is renamed.

One station gives the report; none or two give the usage line and status 2.

Check: the statuses printed are 2, 2, and the good run's report.

A path that fails: using $1 without checking. With no argument, the script would report on a station with an empty name, and end with 0, as if all were well.

When you are stuck: arguments do not arrive as you expect

One argument split in two: quote it when you call the script, "east gate".

Split inside the script: use "$@" and "$1", in double quotes.

An empty $1: no argument was given; check $# first, or use ${1:-default}.

The script reads nothing from read: give it a line through a pipe or a file, or use an argument.

Your turn

A script is run as ./copy.sh a.txt b.txt. What are $0, $2 and $#?Tap to reveal
  1. $0 is the name it was run by.
  2. $2 is the second argument.
  3. $# counts the arguments.

./copy.sh, b.txt and 2.

Why loop over "$@" in quotes?Tap to reveal
  1. Without quotes, an argument with a space is split.

So that each argument stays whole.

./d.sh
./d.sh south
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
station north
station south
  1. With no argument, ${1:-north} gives north.
  2. With one, it gives that argument.

It prints station north, then station south.

Did you know?

$10 is not the tenth

$10 does not give the tenth argument. The bash manual says a positional parameter with more than one digit must be written in braces, as ${10}. Without braces, a digit after the $ can only refer to $1 to $9 or to $0. So $10 is read as $1 followed by a plain 0: with the arguments a to j, it gives a0, not j.

Why it fits here: It answers this topic's question: $10 is $1 and a 0, and the tenth argument needs braces, ${10}.

Source: GNU Bash manual: Positional Parameters

Status 2 for a wrong use

The custom of ending with status 2 after a wrong use matches the shell's own tools. The bash manual says all of bash's builtins return an exit status of 2 to show incorrect usage, generally invalid options or missing arguments. So a script that exits with 2 when its arguments are wrong behaves like cd, read and the other builtins.

Why it fits here: It explains this topic's exit 2: bash's builtins use the same status for incorrect usage.

Source: GNU Bash manual: Exit Status

In one line

A script reads its arguments as $1, $2 and so on; $# counts them, $0 is its own name, and "$@" is every argument, each kept whole. shift moves them down. Check them first, print a usage line to standard error, and exit 2 when they are wrong.

Decisions: if, test and case

At a glance

A script often has to choose: do this if the log exists, and that if it does not. The shell decides by exit statuses, as && and || did.

The word if runs a command, and when it succeeds, runs the lines after then; otherwise those after else, and fi closes it. The command most used after if is [, which checks files with -f and -d, texts with = and -z, and numbers with -eq, -lt and -gt. The word case matches one value against several patterns.

Take a guess: Why does if end with fi, and case with esac?

A script often has to choose: do this if the log exists, that if it does not. The shell decides by exit statuses, as && and || did. if runs a command, and when that command succeeds, with 0, it runs the lines after then; otherwise those after else. The word fi, if backwards, closes it.

The command most often used after if is [, also called test. It checks a condition and succeeds or fails. The spaces inside the brackets are needed, because [ is a command and each part is an argument:

pressure=12
if [ "$pressure" -gt 10 ]; then
  echo high
else
  echo normal
fi
high

Bash also has [[ ]], a newer form that needs fewer quotes and allows && and || inside. elif, else if, adds more choices, checked in order:

pressure=12
if [[ $pressure -lt 5 ]]; then
  echo low
elif [[ $pressure -lt 15 ]]; then
  echo fine
else
  echo high
fi
fine

What test can check

TestTrue whenExample
-f pathit is a file[ -f notes.txt ]
-d pathit is a folder[ -d logs ]
-e pathit exists, of any kind[ -e "$name" ]
a = b, a != bthe texts are equal, or differ[ "$s" = north ]
-z text, -n textthe text is empty, or not[ -z "$1" ]
a -eq b, -ne, -lt, -le, -gt, -genumbers: equal, not equal, less than, at most, greater than, at least[ "$n" -gt 10 ]

Notice that numbers use letters, -lt and -gt. Inside [ ], the signs < and > would be read as redirections; the mistakes section shows what that does.

name=north
[ "$name" = north ] && echo same
[ "$name" != south ] && echo different
[ -z "" ] && echo empty
[ -n "$name" ] && echo "not empty"
same
different
empty
not empty

case: one value, many patterns

When one value must be compared with many choices, case is tidier than a chain of elif. Each choice is a pattern, written like a glob, ending in ), and each list of commands ends with ;;. The pattern * at the end catches everything else:

for s in north south; do
  case $s in
    n*) echo "$s: starts with n" ;;
    *) echo "$s: something else" ;;
  esac
done
north: starts with n
south: something else

The loop around it is the next section's subject; here it runs the case twice, once for each word. esac, case backwards, closes it.

Worked example 3

Before the round, a script must check three names, notes.txt, logs and nothing, and say for each whether it is a file, a folder, or missing.

What we have: a file notes.txt, a folder logs, and no nothing

What we need: one line for each name, with its kind

The plan: for each name, test -f first, then -d, and say missing otherwise

touch notes.txt
mkdir logs
for f in notes.txt logs nothing; do
  if [ -f "$f" ]; then echo "$f is a file"
  elif [ -d "$f" ]; then echo "$f is a folder"
  else echo "$f is missing"
  fi
done
notes.txt is a file
logs is a folder
nothing is missing
  1. The tests are tried in order, and only the first that succeeds runs its line.

notes.txt is a file, logs is a folder, nothing is missing.

Check: each name got exactly one line.

A path that fails: if [ -e "$f" ] alone. It says that notes.txt and logs both exist, but not which is a file and which a folder.

When you are stuck: if takes the wrong branch, or fails strangely

[: missing `]': put spaces inside the brackets, and close them with ].

unary operator expected: a variable was empty and unquoted. Quote it: "$x".

integer expression expected: -lt and -gt need numbers.

A file named 3 appeared: > inside [ ] is a redirection. Use -gt.

Your turn

n=7
if [ "$n" -ge 7 ]; then echo yes; else echo no; fi
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
yes
  1. -ge means greater than or equal.
  2. 7 is equal to 7.

It prints yes.

Which test is true when logs is a folder?Tap to reveal
  1. -d tests for a folder.

[ -d logs ].

Why does [ 5 -gt 3 ] work, while [ 5 > 3 ] goes wrong?Tap to reveal
  1. Inside [ ], > is a redirection.
  2. Numbers are compared with -gt.

Because > sends output into a file named 3.

Did you know?

fi and esac from ALGOL 68

fi and esac are borrowed words. Wikipedia explains that Stephen Bourne had worked on an ALGOL 68C compiler at Cambridge. The shell reused ALGOL 68's if ... fi, case ... esac and do ... od, with done in place of od. Bourne even wrote the shell's C code with macros, so that it read like ALGOL: the Seventh Edition source defines IF as if( and FI as ;}.

Why it fits here: It answers this topic's question: if ends with fi and case with esac because Stephen Bourne borrowed them from ALGOL 68.

Sources: Wikipedia: Bourne shell; Seventh Edition Unix source: usr/src/cmd/sh/mac.h

[ is also a file

The [ of a test is a real program as well as a builtin. On Ubuntu, the coreutils package, which also holds ls and cp, installs a file named /usr/bin/[. The GNU manual calls [ another form of test, and says the brackets must be separate arguments, so [-d /] does not work. bash has its own built-in [, and it too needs each part as a separate word.

Why it fits here: It explains this topic's spaces inside [ ]: [ is a command, both a bash builtin and a program in /usr/bin.

Sources: Ubuntu packages: coreutils file list (noble, amd64); GNU Coreutils manual: test invocation; GNU Bash manual: Bourne Shell Builtins

In one line

The word if runs a command and takes the then branch when it succeeds; elif and else add choices, and fi closes it. The tests [ ] and [[ ]] check files with -f and -d, texts with = and -z, and numbers with -eq, -lt and -gt. The word case matches one value against patterns.

Loops: for and while

At a glance

A watchman's round repeats the same check for every pump. A loop writes the check once and runs it for each one.

The word for takes each word of a list in turn, puts it in a variable, and runs the body between do and done. The list can be numbers, files from a pattern, or "$@". A while loop runs as long as a command succeeds, and while read -r reads a file line by line. The word continue skips to the next round, and break leaves the loop.

Take a guess: Can a for loop run without any list written after it?

The watchman's round repeats the same check for every pump. A loop writes the check once and runs it for each one. for takes each word of a list in turn, puts it in a variable, and runs the body between do and done:

for i in 1 2 3; do echo "pump $i"; done
pump 1
pump 2
pump 3

The list can come from anywhere that makes words: braces for a range, a pattern for files, or "$@" for a script's arguments:

for i in {1..3}; do echo -n "$i "; done
echo
touch a.log b.log
for f in *.log; do echo "log: $f"; done
1 2 3 
log: a.log
log: b.log

echo -n prints without ending the line, so the first loop put its three numbers on one line, and the plain echo after it ended that line.

A pattern that matches nothing

If no file matches, the pattern is left as it is, as the files lesson showed, and the loop runs once with the pattern itself: in an empty folder, the loop above would print log: *.log. Check with [ -e "$f" ] inside the loop when the folder may be empty.

while

while repeats its body as long as a command succeeds. A counter must change inside, or the loop never ends. $((...)) does arithmetic on whole numbers:

n=3
while [ $n -gt 0 ]; do
  echo $n
  n=$((n - 1))
done
echo liftoff
3
2
1
liftoff

Reading a file line by line

The most common while loop reads a file, one line each time round, with read. The file is fed to the whole loop with < after done. read can split each line into several variables at its spaces:

In a folder with gauges.txt: north 12, south 7 and east 18

while read -r pump pressure; do
  echo "$pump reads $pressure"
done < gauges.txt
north reads 12
south reads 7
east reads 18

break and continue

continue skips the rest of this time round and goes on to the next; break leaves the loop at once:

for i in 1 2 3 4 5; do
  if [ $i -eq 2 ]; then continue; fi
  if [ $i -eq 4 ]; then break; fi
  echo $i
done
1
3
WrittenRuns the body
for x in a b conce for each word
for i in {1..10}for each number, 1 to 10
for f in *.logfor each matching file
for a in "$@"for each argument, kept whole
while cmdas long as cmd succeeds
while read -r line; do ... done < filefor each line of the file

Worked example 4

The night's gauge file has a reading for each pump. Report every pump, and mark any reading above 15 as HIGH.

What we have: gauges.txt, with a pump and a pressure on each line

What we need: a line per pump, with HIGH after readings above 15

The plan: read each line into pump and pressure; inside, an if compares the number with -gt

In a folder with gauges.txt: north 12, south 7 and east 18

while read -r pump pressure; do
  if [ "$pressure" -gt 15 ]; then
    echo "$pump: $pressure HIGH"
  else
    echo "$pump: $pressure"
  fi
done < gauges.txt
north: 12
south: 7
east: 18 HIGH
  1. The loop and the if fit inside one another; each line of the file went through the test once.

Only east, at 18, is marked HIGH.

Check: 12 and 7 are not above 15; 18 is.

A path that fails: for line in $(cat gauges.txt). That splits the file at every space, so the loop gets north, then 12, then south, as separate words, and no line stays whole.

When you are stuck: a loop does too much, too little, or never stops

It never stops: the counter in a while loop must change inside it.

It runs once with *.log: no file matched the pattern.

Lines are split into words: read files with while read -r, not for over $(cat).

Arguments are split: loop over "$@", in quotes.

Your turn

for x in a b; do for y in 1 2; do echo -n "$x$y "; done; done
echo
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
a1 a2 b1 b2 
  1. The outer loop takes a, then b.
  2. For each, the inner loop takes 1, then 2.

It prints a1 a2 b1 b2.

How many times does while false; do echo hi; done print hi?Tap to reveal
  1. false fails at once, so the body never runs.

None.

Which loop reads names.txt one line at a time into the variable line?Tap to reveal
  1. while read, with the file fed after done.

while read -r line; do ... done < names.txt.

Did you know?

A for with no list

A for loop can leave out its list. The bash manual says that when in words is not written, the loop runs once for each positional parameter, as if in "$@" had been written. So for arg; do echo "$arg"; done in a script prints each of its arguments on its own line, with any spaces inside them kept.

Why it fits here: It answers this topic's question: a for loop with no list runs over the script's arguments, as if "$@" were written.

Source: GNU Bash manual: Looping Constructs

Even true can fail

while true runs forever because true always succeeds, or nearly always. The GNU manual says true does nothing except return an exit status of 0, and that the shell's built-in colon can do the same, faster. Yet it adds that the program true can be made to fail: asked for --help or --version while its output is closed, it reports a write error and exits with a nonzero status.

Why it fits here: It adds a curiosity to this topic's while loops: true always succeeds, except when asked to print help with nowhere to print it.

Source: GNU Coreutils manual: true invocation

In one line

A for loop runs its body once for each word of a list: numbers, files from a pattern, or "$@". A while loop runs it as long as a command succeeds, and while read -r reads a file line by line. The word continue skips to the next round, and break leaves the loop.

Functions

At a glance

When a script does the same few steps in several places, give the steps a name. A function is a small script inside the script.

Write name() { ... } above the line that calls it, then call it by name, like a command. Inside, it reads $1 and "$@" as a script does. The word local keeps a variable inside the function, and return sets its exit status. Written as $(command), a command's output can be kept in a variable, and $((...)) does arithmetic.

Take a guess: What happens if a function says return 256?

When a script does the same few steps in several places, give the steps a name. A function is a small script inside the script: you define it once, then call it by name, like a command.

greet() {
  echo "Namaste, $1"
}
greet Asha
greet Corin
Namaste, Asha
Namaste, Corin

Inside a function, $1, $2, $# and "$@" are the function's own arguments, not the script's. The definition must come before the first call, because the shell reads the file from the top.

Function

A named group of commands, written name() { ... }, and run by using the name as a command. It takes arguments as $1, $2 and so on, and ends with an exit status, like any command.

local, and an exit status

Variables in a function belong to the whole script unless you mark them local. Use local for every variable that the function makes, so that it cannot clobber one outside. return ends the function with a status, which makes the function a test for if, && and ||:

check() {
  local pump=$1
  if [ "$pump" = seven ]; then return 1; fi
  echo "$pump ok"
}
check north
check seven
echo "status $?"
pump=outer
check east
echo "$pump"
north ok
status 1
east ok
outer

check seven returned 1, a failure, and printed nothing. The last line shows that the function's local pump did not touch the pump outside, which still holds outer.

Keeping a command's output: $(...)

Often you want a command's output in a variable. $(command) runs the command and puts what it prints in its place, without the last line ending. Together with $((...)), for arithmetic, it lets a script count and compute:

In a folder with gauges.txt: north 12, south 7 and east 18

lines=$(wc -l < gauges.txt)
echo "gauges: $lines"
total=0
while read -r pump pressure; do
  total=$((total + pressure))
done < gauges.txt
echo "total pressure: $total"
gauges: 3
total pressure: 37
WrittenIt does
name() { ... }defines a function
name a bcalls it, with $1 = a and $2 = b
local x=1a variable that belongs to this call only
return 1ends the function with status 1
$(command)the command's output, in place
$((a + b))whole-number arithmetic

Worked example 5

The round must check three pumps, and stop at the first one that is not working. Write a function check_pump that reports a pump and fails for pump seven, and use it with && so that the round stops.

What we have: pumps north, seven and east; seven is broken

What we need: north reported, seven refused, east never checked

The plan: the function returns 1 for seven; joining the calls with && stops at the first failure

check_pump() {
  local pump=$1
  if [ "$pump" = seven ]; then
    echo "$pump: FAILED" >&2
    return 1
  fi
  echo "$pump: ok"
}
check_pump north && check_pump seven && check_pump east
echo "status $?"
north: ok
seven: FAILED
status 1
  1. && ran each next call only after a success, so east was never checked, and the line's status is seven's failure.

north: ok, then seven: FAILED, and the round stops with status 1.

Check: east does not appear, because seven failed before it.

A path that fails: joining the calls with ; instead. Then east is checked after the failure, and the status is east's 0, so the round looks as if it went well.

When you are stuck: a function does not behave

command not found for the function: it must be defined above the line that calls it.

A variable outside changed: mark the function's variables local.

$1 is wrong inside the function: it is the function's own argument; pass the script's along, as in check "$1".

A function's status is always 0: end it with return 1 when it fails.

Your turn

double() {
  echo $(( $1 * 2 ))
}
x=$(double 21)
echo "[$x]"
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
[42]
  1. double prints 21 times 2.
  2. $(...) puts that output in x.

It prints [42].

Why use local inside a function?Tap to reveal
  1. Without it, the function's variables belong to the whole script.

So that the function cannot change variables outside it.

How does a function tell its caller that it failed?Tap to reveal
  1. return with a status other than 0.

return 1, or another number but 0.

Did you know?

return 256 means 0

A function's status is small. The bash manual says that when return is given a number, the status is its least significant 8 bits. So statuses run from 0 to 255, and return 256 gives 0, which means success. To hand back a bigger number or a word, a function prints it, and the caller keeps it with $(...).

Why it fits here: It answers this topic's question: return keeps only 8 bits, so return 256 is the same as return 0.

Source: GNU Bash manual: Bourne Shell Builtins

$( ) nests, backquotes struggle

$(...) is the newer form of an older idea, the backquote. The bash manual says command substitutions may be nested, and that nesting the backquoted form needs a backslash before each inner backquote. So $(basename $(pwd)) reads cleanly, while the backquoted form is harder to write and read. Inside double quotes, the manual adds, the result is not split into words.

Why it fits here: It explains this topic's $(command): it nests inside itself with no backslashes, unlike the older backquotes.

Source: GNU Bash manual: Command Substitution

In one line

A function is a named group of commands, written name() { ... } above where it is called; it reads $1 and "$@" like a script. local keeps its variables inside, and return sets its status. $(command) keeps output; $((...)) does arithmetic.

Safe scripts: set -euo pipefail and trap

At a glance

By default a script carries on after a command fails. If a copy fails and the next line clears the log anyway, the log is lost.

Three settings make a script stop instead. The first, set -e, stops it when a command fails; set -u stops it when it uses a name that was never set; and set -o pipefail stops it when any command in a pipe fails. Write set -euo pipefail near the top. The builtin trap runs commands when the script exits, for clean-up, or when a command fails, to report it.

Take a guess: Does set -e stop a script at every failed command?

By default, a script carries on after a command fails. That is how the tired watchman's mistake could happen in a script too: the copy fails, and the next line clears the log anyway. Three settings, switched on with set, make a script stop instead.

SettingMakes the script stop whenWithout it
set -ea command failsit carries on to the next line
set -uit uses a variable that was never setthe name is quietly empty
set -o pipefailany command in a pipe failsonly the last one counts

Here is the same mistake, a mistyped command on line 4, with set -e. The script stops there, with the failed command's status, and two is never printed:

With careful.sh: set -e, echo one, a mistyped command, echo two

./careful.sh
echo $?
one
./careful.sh: line 4: nosuchcommand: command not found
127

set -u turns a misspelt variable, which would be quietly empty, into an error that names it:

With unset.sh: set -u, then a line that uses pump, which was never set

./unset.sh
echo $?
./unset.sh: line 3: pump: unbound variable
1

And pipefail makes a pipe report a failure from any of its commands, not only the last:

With pipe.sh: set -o pipefail, then grep on a missing file, piped into sort

./pipe.sh
grep: nothing.txt: No such file or directory
status 2

Without pipefail, the status would have been sort's 0. The three are usually switched on together, at the top of a script, as set -euo pipefail.

trap: last words

trap sets commands to run when something happens. With EXIT, they run when the script ends, however it ends: the place to remove temporary files. With ERR, they run when a command fails, the place to say that the script stopped early:

trap 'echo "cleaning up"' EXIT
echo working
working
cleaning up

The nightly round, written safely

Here is the watchman's round as a script that cannot clear a log it has not copied:

nightly.sh

#!/bin/bash
# the nightly round: copy the day's log, clear it, report
set -euo pipefail
trap 'echo "round stopped early" >&2' ERR

day=${1:-today}
mkdir -p archive
cp "logs/$day.log" "archive/$day.log"
: > "logs/$day.log"
lines=$(wc -l < "archive/$day.log")
echo "round done: $lines lines kept for $day"

Read it from the top. The second line switches on all three safety settings. The trap prints a warning, to standard error, if any command fails. day is the first argument, or today. The cp copies the day's log into the archive. The line : > "logs/$day.log" empties the log: : is a command that does nothing, and the > empties the file. The last lines count what was kept, and report.

Worked example 6

Run the nightly round twice: once for today, whose log exists, and once for friday, whose log does not. Check that nothing is cleared when the copy fails.

What we have: nightly.sh, a logs folder with today.log of 2 lines, and no friday.log

What we need: today's log copied and cleared; for friday, a stop before anything is cleared

The plan: run it with no argument, then with friday; check the status, and count the lines left in today.log after each

With nightly.sh, shown above, and logs/today.log of 2 lines

./nightly.sh
echo "status $?"
wc -l < logs/today.log
round done: 2 lines kept for today
status 0
0
  1. Today's 2 lines went to the archive, and the log was emptied afterwards.

The same, asked for friday

./nightly.sh friday
echo "status $?"
wc -l < logs/today.log
cp: cannot stat 'logs/friday.log': No such file or directory
round stopped early
status 1
2
  1. The copy failed, so set -e stopped the script on that line, the ERR trap said so, and the line that empties a log never ran.

Today: 2 lines kept. Friday: stopped early, with status 1, and nothing cleared.

Check: today.log still has its 2 lines after the friday run.

A path that fails: the same script without set -e. The cp fails, the next line empties a log anyway, and the report says round done: the watchman's mistake, made by a machine.

When you are stuck: a script stops, or will not stop

unbound variable: set -u found a name that was never set; set it, or use ${name:-default}.

It stopped on a command that may fail harmlessly: write cmd || true, so that the failure is expected.

It carried on after a failure: put set -euo pipefail near the top.

Clean-up did not run: put it in a trap on EXIT.

Your turn

What does set -e do when a command fails?Tap to reveal
  1. It ends the script at that command.

It stops the script, with that command's status.

Why add pipefail to set -e?Tap to reveal
  1. Without it, a pipe's status is only its last command's.
  2. So a failure early in a pipe would not stop the script.

So that a failure anywhere in a pipe counts.

trap 'echo bye' EXIT
echo hello
exit 3
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
hello
bye
  1. echo hello runs first.
  2. exit ends the script, and the EXIT trap runs as it ends.

It prints hello, then bye.

Did you know?

set -e lets some failures through

set -e does not stop a script at every failure. The bash manual lists where a failed command is let through. Those places are the test of an if, the list after while or until, and any part of a && or || list except the last. They also include a pipeline's commands before the last, unless pipefail is on, and a command after a !. So if grep -q x file never stops the script, which is what an if needs.

Why it fits here: It answers this topic's question: set -e lets failures through inside if tests, while loops, && and || lists, and pipelines.

Source: GNU Bash manual: The Set Builtin

pipefail joined POSIX in 2024

set -o pipefail is now a standard. POSIX.1-2024, the edition known as Issue 8, records that it added -o pipefail to the set command; bash had the option already. The standard also says a pipeline uses the pipefail setting in force when the pipeline begins, not the one in force when its status is set.

Why it fits here: It shows that this topic's pipefail is now part of the POSIX standard, added in its 2024 edition.

Sources: POSIX.1-2024: Shell Command Language; GNU Bash manual: The Set Builtin

In one line

The setting set -e stops a script at a failed command, set -u at an unset name, and pipefail counts failures anywhere in a pipe. Write set -euo pipefail near the top. The builtin trap runs commands on EXIT, for clean-up, or on ERR, to report a failure.

Where it is used

Scripts are how routine work gets done the same way every time, on servers and on your own machine. Here is where each idea of this lesson does its work.

What you learnedWhere it is usedA real example
a script with a shebangany task done more than twicesetting up a new project
arguments and a usage linetools for other peoplea backup script told which folder
if and testchecking before actingonly copy if the file exists
for and while readthe same work on many thingsevery log of the night, every line of a list
functionssteps used in several placesa check run for each server
set -euo pipefailscripts that must not run on after a mistakea deploy script, the next step's tools
trapclean-up and warningsremoving temporary files at the end

Mistakes and debugging

These are the slips that people meet most often in scripts. Every output below is the real one, from the code shown.

1. A missing space in a test

x=5
if [$x -gt 3]; then echo big; fi
bash: line 2: [5: command not found

[ is a command, so it needs a space after it, and ] is its last argument. The fix: if [ "$x" -gt 3 ].

2. > inside [ ]

if [ 5 > 3 ]; then echo yes; fi
ls
yes
3

No error, which is worse: > made a file named 3, and the test only checked that 5 is not empty. The fix: [ 5 -gt 3 ].

3. An empty variable, unquoted

x=
if [ $x = yes ]; then echo yes; fi
bash: line 2: [: =: unary operator expected

With x empty and unquoted, [ received only = and yes. The fix: [ "$x" = yes ].

4. A for loop over a file's text

In a folder with gauges.txt: north 12, south 7 and east 18

for line in $(cat gauges.txt); do echo "[$line]"; done | head -n 3
[north]
[12]
[south]

The text was split at every space, not at line ends. The fix: while read -r line; do ... done < gauges.txt.

5. Carrying on after a failure

With risky.sh: cp today.log archive.log, then rm today.log; and no today.log

./risky.sh
ls
cp: cannot stat 'today.log': No such file or directory
rm: cannot remove 'today.log': No such file or directory
risky.sh

The copy failed, and the script went on to the removal anyway. Had the log existed, and the copy failed for another reason, such as a full disk, the log would now be gone, uncopied. The fix: set -euo pipefail at the top.

The debugging corner: bash -x

Run a script with bash -x script.sh to see each command printed, with a + in front, after its variables are filled in and just before it runs. The last line printed before things go wrong is the line to look at.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

The lesson in code: a script written, made runnable and run

cat > check.sh <<'END'
#!/bin/bash
set -euo pipefail
trap 'echo "check ended"' EXIT
limit=${1:-15}
report() {
  local pump=$1 pressure=$2
  if [ "$pressure" -gt "$limit" ]; then
    echo "$pump: $pressure HIGH"
  else
    echo "$pump: $pressure"
  fi
}
while read -r pump pressure; do
  report "$pump" "$pressure"
done < gauges.txt
END
chmod +x check.sh
./check.sh 10
north: 12 HIGH
south: 7
east: 18 HIGH
check ended
When you seeIt meansLook at
Permission denied, status 126the script has no xchmod +x
[5: command not foundno space after [[ "$x" -gt 3 ]
unary operator expectedan empty variable, unquoted, in a test"$x"
integer expression expected-gt or -lt given textthe value
unbound variableset -u found an unset nameits spelling, or ${name:-default}
a file named 3> inside [ ]-gt
words split from a filefor over $(cat file)while read -r
a script ran on after a failureno set -eset -euo pipefail

The story: The tunnels read for themselves

You write the round on a sheet, with its first line naming who is to read it. You give it the mark that lets it run, and a name for each thing that changes. It stops at the first thing that goes wrong, rather than carrying on regardless. It says what it did, and it can be told which station to start from.

At midnight the round runs by itself, and the watchman sleeps, and in the morning the log is copied and the report is on the warden's desk.

Warden Rao reads the report, and then the sheet. She hands you a lantern of your own. "The Archivists are next," she says. "They keep every sheet anyone ever wrote, and every change to it. You will want that."

Reagents gathered: shebang, script, argument, if, for loop, set -e.

Sources

  • GNU Bash Reference Manual (GNU Free Documentation License 1.3 or later (the manual's copying notice, read 2026-11-06); facts and ideas only)
  • GNU Coreutils manual (GNU Free Documentation License 1.3 or later (the manual's copying notice, read 2026-11-06); facts and ideas only)