I've written more shell scripts than I can count, but I still stumble upon tricks that honestly blow my mind far too often than I care to admit. Latest thing that blew my head clean off? The shell colon.
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?
Note: Want your mind blown straight away? See more colons in the limelight.
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 fi echo "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 !"
... continue reading