In the baroque world of shell scripting, sometimes it gets boring to retrieve parameters and issue a decent error if they're bad.
I'm probably not inventing anything new here, but here's my approach:
Define a help function;
Set it as trap for
ERR
andEXIT
(executed on error or upon exit)Set the
-e
flag, so any application returning failure (non-zero) will cause the script to exit;Ask the parameters with
${parameter:?error message}
. This will explain the message and fail (triggering the trap). Other failed tests will also fail in the same way;Disable the trap (or set it differently) and continue.
A little example of a tool I'm using:
#!/bin/bash
#
# Compare two log files using the diff tool.
helpme() {
set +x
echo "usage: $0 \$test_regex \$file_one $file_two"
echo
echo "The files must exist. Lines not matching the regex will be"
echo "filtered in both files".
}
trap helpme ERR EXIT
set -e
test=${1:?test regex missing}
[ -e "${2:?file one}" ];
[ -e "${3:?file two}" ];
trap - ERR EXIT
flt () { perl -nE "m/$test/ or next; s/^.*\(\) //; print"; }
exec diff -U100 <(flt < $2) <(flt < $3)