Missing required arguments in shell scripts? Use the colon. | Filip Roséen - refp.se
Table of Contents
- In a land far-far away..
- Checking for required arguments * Parameter expansion and the story of :?
- That.. other colon
- Con-colon-sion
In a land far-far away.. #
... there was once a far too cold cup of coffee next to a freshly brewed far-too-hot one. Four different terminals where three could have been closed an hour ago, and a shell script which I really (really) did not want to write.
Who would have thought a single colon would be the one to save the `day` night?
Checking for required arguments #
This is a familiar dance, it's pretty much muscle memory by this point. You have a script, it takes a few arguments, and some of them are mandatory; alright, an if-statement like so many times before:
if [ -z "$1" ]; then
echo "missing argument, aborting!" 1>&2
exit 1
fiecho "Hello: $1!"
Though.. what if I told you the above four lines could be replaced by just... one?
: ${1:?missing argument, aborting!}echo "Hello $1!"
$ bash example.sh
example.sh: line 3: 1: missing argument, aborting!$ bash example.sh refp
Hello refp!
Parameter expansion and the story of `:?` #
There are two things going on in the previous snippet, and you are correct in identifying that one part is using parameter expansion:
That.. other colon #
So that's one colon, but what about that other one, the one who sits alone at the beginning of the line?
Con-colon-sion #
So, if you are like me and prefer less typing (gotta go fast) — the null command and parameter expansion are a good pair to remember.
while : "do the hustle"; do
echo "I love colons"
sleep 1
done