Bash scripts tend to follow a life time. They start as a long bash command dumped into a file for future use. They then get formatted and prettified when others want to use them.
When your script gets used by others it’s a great idea to add some basic error checking and help information. Let’s look at how to do this.
The example script, print-string.sh
, does nothing else but print a string passed to it. Here it is:
#! /usr/bin/env bash
set -euo pipefail
printf "$1\n"
When invoked all it does is print whatever was passed to it e.g.:
$ ./print-string.sh "Hello World!"
Hello World!
Unfortunately it fails in an unhelpful way e.g. no string is passed:
$ ./print-string.sh
./bad-fail.sh: line 4: $1: unbound variable
Let’s make it more helpful.
The first thing to check is that there is the user has passed something to the script and exits helpfully with if they haven’t.
The following if
statement checks that exactly one variable has been passed to the script:
#! /usr/bin/env bash set -euo pipefail set -euo pipefail
if [ $# -ne 1 ]; then
printf "Usage: ./hello-world.sh \"string to print\"\n"
exit 1
fi
printf "$1\n"
The if
statement checks that the total number of options $#
is exactly equal to 1
with the -ne
test. Any more or less and it prints the script usage info.
Now, lets add some help. The usual way to request help from a Bash scrip is to use -h
or -help
. Let’s check for both with a case statement.
#! /usr/bin/env bash
set -euo pipefail
if [ $# -ne 1 ]; then
printf "Usage : ./hello-world.sh \"string to print\"\n"
exit 1
fi
case $1 in
"-help" | "-h" )
printf "Usage : ./hello-world.sh \"string to print\"\n"
;;
*)
printf "$1\n"
;;
esac
The case
statement here checks the supplied argument, $1
, if it is a -help
or -h
. It is is then it prints the usage information. You can put as many options here as you want separated by |
s.
The second case statement *)
matches everything that does not match any other case statement. It then runs the print command with the contents of the string.
Now, we’ve got a helpful script that will help our your other sysadmins!