Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Part 2 · System administration · Lesson 11 · 35 minutes

Write a safe shell script

After this lesson you can
  • Write a script that takes arguments, makes decisions and returns an exit code
  • Quote variables and stop on errors so that a script fails loudly
  • Test a script with a fixed log and read its exit codes
Lab files of this lesson (21)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

Every morning you check a server by hand: who failed to log in, and which files grew too big. Your lead wants a script that any colleague can run, that tells its result in words and in an exit code, and that fails loudly when it is used wrongly. You see the way with a log checker. Then you write a second script from a short specification. The next lesson runs it by itself every morning.

Recall

What does "sha256sum -c LIST" return when one file does not match, and why does it matter for a script?

It returns the exit code 1. A script can stop on it, so a changed file is never used.

Which stream carries error messages, and how do you send it to a file?

stderr, stream 2. 2> FILE sends it to a file (lesson 6 of Part 1). A script uses the same stream for its usage and error lines.

The idea

A shell script is a text file of commands. The first line, the shebang (#!), names the program that runs it. A script that you run as ./name.sh needs the execute bit (lesson 10 of Part 1).

Every command ends with an exit code: 0 means success and any other number means failure. $? holds the code of the last command. if, && and || act on it (step 3 shows if and the loops).

SyntaxMeaning
name=valueSet a variable. No spaces around =.
"$name"Read it. Always use double quotes.
$1, $2, $#, "$@"The arguments, how many there are, and all of them.
$(command)The output of a command, as text.
set -euo pipefailStop at an error (-e), at an unset variable (-u), and when any command in a pipe fails.

The log checker of the worked example follows this flow:

What check-log.sh does
Read argumentsCount failuresRank addressesCompareExit codelog file and limitgrep, cut, sort, uniq -cfor each address, count versus limit0 for clean, 1 for foundRead argumentsCount failuresRank addressesCompareExit code1234
  1. Read arguments → Count failures: log file and limit
  2. Count failures → Rank addresses: grep, cut, sort, uniq -c
  3. Rank addresses → Compare: for each address, count versus limit
  4. Compare → Exit code: 0 for clean, 1 for found

Worked example

1. Write and run a first script

${1:-world} means "the first argument, or world if there is none". Save the script as hello.sh in a new folder.

mkdir -p ~/krlab/linux-admin/sh && cd ~/krlab/linux-admin/sh

sh/hello.sh

#!/usr/bin/env bash
name=${1:-world}
echo "hello, $name"
./hello.sh
chmod +x hello.sh
./hello.sh "Ann Lee"
bash: ./hello.sh: Permission denied
hello, Ann Lee

The first run fails, because the file has no execute bit. After chmod +x it runs. The quotes keep Ann Lee as one argument.

2. See why quoting matters, and handle errors

A variable without quotes is split at every space. Here the file name has a space in it. false is a command that always fails, true one that always succeeds, and bash -c 'TEXT' runs the text as a tiny script.

echo "my data" > "my notes.txt"
f="my notes.txt"
cat $f
cat "$f"
bash -c 'false; echo "still running"'
bash -c 'set -e; false; echo "never printed"'
bash -c 'false | true; echo "pipe exit: $?"'
bash -c 'set -o pipefail; false | true; echo "pipe exit: $?"'
cat: my: No such file or directory
cat: notes.txt: No such file or directory
my data
still running
pipe exit: 0
pipe exit: 1

The first cat got two names. With an empty variable, rm -rf $dir/* becomes rm -rf /*. Quote every variable, and stop on an empty one with "${dir:?dir is not set}". By default a script carries on after a failed command. With set -e it stops, and with pipefail a failure anywhere in a pipe counts. grep exits with 1 when it finds nothing, which stops the script under set -e. When "no match" is fine, write grep ... || true.

3. Choose and repeat

A script chooses with if and repeats with for and while. Each form ends with a word that closes it: fi is if backwards, and done closes a loop.

FormWhat it does
if [[ TEST ]]; then ...; else ...; fiRuns the first part when the test is true, and the else part when not.
for x in a b c; do ...; doneRuns the lines once for each word, with x set to that word.
while TEST; do ...; doneRuns the lines again and again as long as the test is true.
$(( n + 1 ))Calculates with whole numbers, and gives the result as text.
(( n ))A test that is true when the number is not 0.

[[ ... ]] is the test of the shell. Its words: -z TEXT is true for empty text and -n TEXT for text that is not empty. -r FILE is true when you may read the file. A -ge B means "A is greater than or equal to B", and -eq, -gt and -lt mean equal, greater than and less than. ! turns a test round, and && inside the brackets means "and". Try each form once:

n=0
for name in ann bob; do
    n=$((n + 1))
    echo "$n: $name"
done
while [[ $n -lt 4 ]]; do
    n=$((n + 1))
done
echo "n is $n"
word=""
if [[ -z $word ]]; then echo "word is empty"; else echo "word is $word"; fi
if [[ -r hello.sh && $n -ge 3 ]]; then echo "readable, and n is at least 3"; fi
(( n )) && echo "n is not 0"
1: ann
2: bob
n is 4
word is empty
readable, and n is at least 3
n is not 0

The loop ran twice and n became 2. The while loop then added one until n was 4. The last line shows that (( n )) works like a test: && runs the echo only when the test is true.

4. Write the log checker

The script reads a log, counts the failed logins of each address, and flags the addresses at or above a limit. First save the log that it reads, a fixed copy of a login log, as auth.log.

sh/auth.log

Nov 21 08:10:01 krbox sshd[1101]: Failed password for root from 203.0.113.50 port 40001 ssh2
Nov 21 08:10:05 krbox sshd[1103]: Failed password for root from 203.0.113.50 port 40003 ssh2
Nov 21 08:10:09 krbox sshd[1105]: Failed password for invalid user admin from 203.0.113.50 port 40005 ssh2
Nov 21 08:10:14 krbox sshd[1107]: Failed password for invalid user pi from 203.0.113.50 port 40007 ssh2
Nov 21 08:10:18 krbox sshd[1109]: Failed password for root from 203.0.113.50 port 40009 ssh2
Nov 21 08:12:44 krbox sshd[1110]: Failed password for invalid user git from 198.51.100.7 port 40100 ssh2
Nov 21 08:13:02 krbox sshd[1111]: Accepted publickey for dana from 192.0.2.44 port 52100 ssh2

Read these parts before you read the script:

  • usage() { ...; } defines a function, a named block of commands. >&2 sends a message to stderr, and exit 2 ends the script with code 2.
  • [[ $# -ge 1 ]] || usage calls the function when there is no argument ($# is the number of arguments). The if blocks use the tests of step 3.
  • $(grep -c ... || true) puts the output of a command into a variable.
  • The pipe ends in awk -v limit="$limit" '$1 >= limit {...}'. -v hands the shell variable to awk, and the action runs for each line whose first field (the count of uniq -c) is at or above the limit.

sh/check-log.sh

#!/usr/bin/env bash
# Report addresses with many failed SSH logins.
set -euo pipefail

usage() {
    echo "usage: $0 LOGFILE [LIMIT]" >&2
    exit 2
}

[[ $# -ge 1 ]] || usage
log=$1
limit=${2:-3}

if [[ ! -r $log ]]; then
    echo "cannot read: $log" >&2
    exit 1
fi

total=$(grep -c "Failed password" "$log" || true)
echo "failed logins in $log: $total"

alerts=$(grep "Failed password" "$log" | grep -oE "from [0-9.]+" | cut -d' ' -f2 \
    | sort | uniq -c | sort -rn \
    | awk -v limit="$limit" '$1 >= limit {print "ALERT " $2 " made " $1 " failures"}' || true)

if [[ -n $alerts ]]; then
    echo "$alerts"
    exit 1
fi

5. Run it and read the exit codes

chmod +x check-log.sh
./check-log.sh auth.log; echo "exit: $?"
./check-log.sh auth.log 9; echo "exit: $?"
./check-log.sh; echo "exit: $?"
./check-log.sh nofile.log; echo "exit: $?"
failed logins in auth.log: 6
ALERT 203.0.113.50 made 5 failures
exit: 1
failed logins in auth.log: 6
exit: 0
usage: ./check-log.sh LOGFILE [LIMIT]
exit: 2
cannot read: nofile.log
exit: 1
The command ./check-log.sh auth.log 9
./check-log.sh$0: the scriptauth.log$1: the log file9$2: the limit./check-log.sh$0: the scriptauth.log$1: the log file9$2: the limit

The codes are 0 clean, 1 something found or a read error, 2 wrong use. bash -n check-log.sh reads a script and reports syntax errors without running it.

Your turn

Write a script bigfiles.sh that finds the files which are too big. Lesson 12 schedules it.

First build the data. head -c 50 takes the first 50 bytes of its input, /dev/zero is an endless source of zero bytes, and tr '\0' x turns each zero byte into the letter x. So each line makes a file of an exact size. Run this block once. It is not the task.

mkdir -p ~/krlab/linux-admin/sh-task/data && cd ~/krlab/linux-admin/sh-task
head -c 50 /dev/zero | tr '\0' x > data/a.txt
head -c 100 /dev/zero | tr '\0' x > data/e.txt
head -c 150 /dev/zero | tr '\0' x > data/b.log
head -c 300 /dev/zero | tr '\0' x > data/c.log
head -c 2000 /dev/zero | tr '\0' x > data/d.bin

The specification of bigfiles.sh:

  1. It takes a directory as argument 1 and a limit in bytes as optional argument 2. The default limit is 100.
  2. It prints the path of each regular file in the directory that is larger than the limit, one for each line, in sorted order. A file of exactly the limit is not too big.
  3. Its last line is big files: N, where N is the number of files that it printed.
  4. Its exit code is 1 when N is more than 0, and 0 when N is 0. Without an argument it prints a usage line to stderr and exits with 2.
  5. It stops on errors and on unset variables, and it quotes every variable.

There are no steps here. Use the tools of the worked example (find can test the size). Run your script on the folder data and answer from your own terminal.

Last, run bash -n on your script, and run it with the limit 5000. The exit code must be 0.

Check yourself

Why does "rm -rf $dir/*" frighten a reviewer?

If dir is empty or unset, the shell expands the line to rm -rf /*. Quoting alone does not help here. Use set -u or "${dir:?}" so that the script stops, and check the value before you delete.

Under "set -e", the line "grep error log.txt" stops your script when the log is clean. Why, and what do you do?

grep exits with 1 when nothing matches, and set -e treats that as a failure. If "no match" is normal, write grep error log.txt || true, or test with if grep -q ....

A script has no "exit" line, and its last command fails. What exit code does the script return?

The code of the last command that ran. A script that ends after a failed command therefore reports failure, and one that ends after a success reports 0. Write exit with a number when the code must mean something.

Why does check-log.sh exit with 2 for a wrong call and with 1 when it finds addresses?

Two numbers let the caller tell the cases apart: 2 means "you used me wrongly", 1 means "I ran and found something". Another script or a scheduler can then react in a different way to each.

Field notes

  • Start every script with set -euo pipefail. Know the limits: set -e has odd rules inside if conditions and in functions that are tested, so check the results that matter.
  • Create temporary files with mktemp and remove them with a trap: trap 'rm -f "$tmp"' EXIT. A fixed name such as /tmp/out is open to symlink attacks.
  • Do not build a command from untrusted text, and never use eval on it. Pass values as arguments. Use -- before file names that can start with a dash: rm -- "$file".