Pages: Welcome | Projects

Handy help-me pattern

2017/3/16
Tags: [ Hacking ] [ shell ]

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:

  1. Define a help function;

  2. Set it as trap for ERR and EXIT (executed on error or upon exit)

  3. Set the -e flag, so any application returning failure (non-zero) will cause the script to exit;

  4. 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;

  5. 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)