tech katta

Shell scripting: variables, if, loops, exit codes and set -euo pipefail

Lesson 12 of 23 · 6 min readFree

In this lesson

Turn the commands you have learned into a safe, repeatable script with variables, conditions, loops, functions and strict error handling, and customise your shell with .bashrc.

On this page
  1. Why this matters
  2. Your first script
  3. Conditions: if
  4. Loops
  5. Functions and case
  6. Fail fast: set -euo pipefail
  7. A complete example
  8. .bashrc: customising your shell
  9. Try it

A shell script is a text file of commands that run in order. Once you have typed the same four commands for the third time, put them in a script. Scripts are how backups, health checks and deploys are automated, and a small, careful one is worth more than a big clever one.

Why this matters#

A deploy done by hand depends on memory: someone forgets a step, runs a command in the wrong folder, or carries on after an error. A script does the same steps every time, and with a few safety settings it stops at the first failure instead of making things worse. The settings in this lesson are the difference between a script that helps and one that quietly deletes the wrong folder.

Every script in this lesson was written to a file and run on a Linux machine; the output shown is real.

Your first script#

A script is a file that starts with a shebang, a first line saying which program should run it, followed by commands. Make it executable (lesson 7) and run it with a path (lesson 1).

Shell
#!/usr/bin/env bash
name="${1:-world}"
count=3
echo "Hello, $name"
echo "Arguments: $# first=$1"
echo "Script: $0"
today=$(date +%F)
echo "count + 2 = $((count + 2))"
Shell
chmod +x hello.sh
./hello.sh
./hello.sh Asha
Text
Hello, world
Arguments: 0 first=
Script: ./hello.sh
count + 2 = 5
Hello, Asha

(The second run's output is cut to its first line.) A lot is happening in these few lines:

  • #!/usr/bin/env bash runs the script with whatever bash is first on PATH.
  • name=value sets a variable. There must be no spaces around the =. Read it back with $name.
  • $1, $2 are the script's arguments, $# is how many were given and $0 is the script's own name.
  • ${1:-world} means "use $1, or world if it is empty". This is how you give a setting a default.
  • $(command) runs a command and substitutes its output. $((...)) does integer arithmetic.
  • Variables hold text. Always put double quotes around them when you use them: "$name".

Use single quotes when you want no substitution at all, and double quotes when you want $variables expanded. Variables you want child processes to see must be exported: export APP_ENV=production.

Conditions: if#

if runs a command and checks its exit code (lesson 1). Zero counts as true. The tests you write inside [[ ... ]] are commands too.

Shell
#!/usr/bin/env bash
file="$1"
if [[ -z "$file" ]]; then
  echo "usage: check.sh FILE" >&2
  exit 2
elif [[ -f "$file" && -s "$file" ]]; then
  echo "$file exists and is not empty"
elif [[ -f "$file" ]]; then
  echo "$file is empty"
  exit 1
else
  echo "$file not found"
  exit 1
fi
Text
usage: check.sh FILE
  exit=2
full.txt exists and is not empty
  exit=0
empty.txt is empty
  exit=1
missing.txt not found
  exit=1

Tests worth knowing:

  • -z "$x" is true if the string is empty, and -n "$x" if it is not.
  • -f path is true for a regular file, -d path for a directory, -e path for anything that exists, and -s path for a file with content.
  • == and != compare strings. -eq, -ne, -lt, -gt compare numbers: [[ $n -lt 3 ]].
  • && and || combine tests, and ! negates.

Spaces inside the brackets are required: [[ -f $x ]] works, [[-f $x]] does not. Messages for humans go to stderr with >&2, so they do not pollute output that other commands might read. exit N ends the script with that code, so callers and CI can tell what happened. By convention 0 is success, 1 is a general failure and 2 is wrong usage.

You can also use && and || between commands, as a short if:

Shell
grep -q ERROR access.log && echo found || echo "no ERROR lines"
Text
no ERROR lines

grep -q prints nothing and only sets the exit code. This chain has a catch: A && B || C runs C if A fails or if B fails. For anything more than a single echo, use if.

Loops#

for goes through a list and while repeats while a command succeeds.

Shell
for f in logs/*.log; do
  echo "file: $f"
done
n=0
while [[ $n -lt 3 ]]; do
  n=$((n+1))
done
echo "n=$n"
Text
file: logs/a.log
file: logs/b c.log
n=3

Notice that the file named b c.log, with a space, was handled as one item. That is because we looped over a wildcard and quoted "$f" when using it. Compare the same job done by parsing ls:

Shell
for f in $(ls logs); do echo "[$f]"; done
Text
[a.log]
[b]
[c.log]

The shell split the name at the space. Loop over a pattern, never over the output of ls, and quote your variables. To read a file or command output line by line, use while read -r line; do ...; done < file.

Functions and case#

A function groups commands. local keeps a variable inside it, and return sets its exit code, while its output goes to stdout like any command.

Shell
f(){ local x=$1; echo "got $x"; return 3; }
f hi
echo "rc=$?"
Text
got hi
rc=3

case matches one value against several patterns, which is cleaner than a ladder of if statements. This one chooses by environment name:

Shell
case "$env" in
  prod) echo "production" ;;
  stag*|dev) echo "non-production" ;;
  *) echo "unknown environment" >&2; exit 1 ;;
esac

Fail fast: set -euo pipefail#

By default a script keeps going after a failure. Compare two scripts that both run false (a command that always fails) between two echo lines:

Text
$ ./unsafe.sh
step 1
step 2 still runs
$ ./safe.sh        # same, but with set -euo pipefail at the top
step 1

The safe script stopped at false and exited with code 1. Imagine the step that failed was cd /srv/app/releases/new and the next one was rm -rf *. Without the safety line, the script would delete files in whatever folder it happened to be in. The line is made of three parts:

  • set -e exits as soon as a command fails.
  • set -u treats an unset variable as an error, instead of an empty string. This catches typos like $TARGT_DIR.
  • set -o pipefail makes a pipeline fail if any command in it fails, not only the last (lesson 5).
Shell
set -u
echo "deleting ${TARGET_DIR}/old"
Text
unset.sh: line 3: TARGET_DIR: unbound variable
exit=1

Without -u, that line would have printed deleting /old, which is exactly how scripts delete the wrong thing. Put set -euo pipefail near the top of every script you write. It has exceptions: a command in an if condition or before || is allowed to fail. If you expect a failure, say so, as in grep -q x file || true.

A complete example#

This backup script ties the pieces together. It makes an archive, then checks that the app answers, and cleans up whatever happens, using trap to run a function when the script exits.

Shell
#!/usr/bin/env bash
# Archive the app folder, then check that the app answers.
set -euo pipefail

APP_DIR="${APP_DIR:-/srv/app/current}"
BACKUP_DIR="${BACKUP_DIR:-/srv/app/backups}"
HEALTH_URL="${HEALTH_URL:-http://127.0.0.1:5100/health}"
stamp=$(date +%Y%m%d)

log() { echo "[backup] $*"; }

cleanup() {
  rc=$?
  if [[ -n "${tmp:-}" ]]; then rmdir "$tmp" 2>/dev/null || true; fi
  log "finished with exit code $rc"
}
trap cleanup EXIT

command -v tar >/dev/null || { log "tar is not installed" >&2; exit 1; }
mkdir -p "$BACKUP_DIR"
tmp=$(mktemp -d)
tar -czf "$tmp/app-$stamp.tar.gz" -C "$APP_DIR" .
mv "$tmp/app-$stamp.tar.gz" "$BACKUP_DIR/"
log "wrote $BACKUP_DIR/app-$stamp.tar.gz"

if curl -sf "$HEALTH_URL" >/dev/null; then
  log "app is healthy"
else
  log "app did not answer" >&2
  exit 1
fi

We ran it with APP_DIR and BACKUP_DIR pointed at a scratch folder and a local test server, then again with HEALTH_URL pointed at a port where nothing listens:

Text
[backup] wrote /srv/l12/backups/app-YYYYMMDD.tar.gz
[backup] app is healthy
[backup] finished with exit code 0
exit=0
--- fail case
[backup] wrote /srv/l12/backups/app-YYYYMMDD.tar.gz
[backup] app did not answer
[backup] finished with exit code 1
exit=1

(We replaced the real date with YYYYMMDD.) Settings come from environment variables with defaults, so the same script works on your laptop and on the server. The trap ran its cleanup in both cases. The failure still gave exit code 1, which a scheduler or CI job would treat as failed. Before running a script, check its syntax with bash -n script.sh. The tool shellcheck is excellent at finding quoting mistakes, and you can install it with apt (lesson 11).

.bashrc: customising your shell#

Each time you open an interactive bash shell, it reads ~/.bashrc. This is the place for aliases, your PATH additions and small helper functions. We tested a two-line example:

Shell
export PATH="$HOME/.local/bin:$PATH"
alias ll='ls -lah'
Text
ll is aliased to `ls -lah'
/root/.local/bin

The first line puts your own folder at the front of PATH (lesson 1), and the second creates a shortcut. Changes apply to new shells; run source ~/.bashrc to load them into the current one. A login shell, such as an SSH session, reads ~/.profile first, and on Ubuntu that file loads .bashrc for you. Do not put heavy or output-producing commands in .bashrc: tools like scp and rsync start shells too, and unexpected output can break them. Scripts do not read .bashrc, which is another reason a script must set what it needs itself.

Try it#

  1. Write hello.sh as above. Run it with no argument and with one. Add a default for a second argument.
  2. Write check.sh, run it on a file that exists, one that is empty and one that does not exist, and print $? after each.
  3. Write a loop that prints the size of each .log file in a folder using wc -c. Include a file with a space in its name to prove you handled it.
  4. Create safe.sh and unsafe.sh as in the lesson and compare their output and exit codes.
  5. Write a small backup.sh of your own that archives a folder with tar, prints where it wrote the file, and exits with code 1 if the folder does not exist. Run bash -n on it first.