Giving an Error Message for Unset Parameters
Problem
Those shorthands for giving a default value are cool, but maybe you need to force the
users to give you a value, otherwise you don’t want to proceed. Perhaps
if they left off a parameter, they don’t really understand how to invoke
your script. You want to leave nothing to guesswork. Is there anything
shorter than lots of if
statements to
check each of your several parameters?
Solution
Use the ${:?} syntax when referring to the parameter. bash will print an error message and then exit if the parameter is unset or null.
#!/usr/bin/env bash # cookbook filename: check_unset_parms # USAGE="usage: myscript scratchdir sourcefile conversion" FILEDIR=${1:?"Error. You must supply a scratch directory."} FILESRC=${2:?"Error. You must supply a source file."} CVTTYPE=${3:?"Error. ${USAGE}"}
Here’s what happens when we run that script with insufficient arguments:
$ ./myscript /tmp /dev/null ./myscript: line 5: 3: Error. usage: myscript scracthdir sourcefile conversion $
Discussion
The check is made to see if the first parameter is set (or null) and if not, it will print an error message and exit.
The third variable uses another shell variable in its message. You can even run another command inside it:
CVTTYPE=${3:?"Error. $USAGE. $(rm $SCRATCHFILE)"}
If parameter three is not set, then the error message will contain
the phrase “Error.”, along with the value of the variable named $USAGE
and then any output from the command which removes the filename named ...
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.