Bash Tips: Giving Feedback

There's one piece of code I duplicate constantly, an I'm blogging it to save time in the future. It's also a useful snippet for anyone that writes lots of scripts.

Any time you write a script, you want to send feedback to the user. Possibly brief informational messages, debugging information, error reports, etc. You could just echo these, but that's a very simplistic approach. I prefer to touch up the messages a bit before sending them out, as it improves readability.

Here is the code I use to filter all status messages, nestled among example test code:

#!/bin/sh

function message() {
    echo "$0[$$]: $@"
}

function error() {
    message "$@" >/dev/stderr
}

case "$1" in
    '') echo "usage: $0 [-e|-m] [--] message" ; exit 1 ;;
    -e) shift ; error "$@" ;;
    -m|--) shift ; message "$@" ;;
    -*) error "invalid argument: $1" ; exit 1 ;;
    *) message "$@" ;;
esac

Running this program will format message like so:

scriptname[2054]: message

Where "scriptname" is the name of the script, "2054" is the process ID, and "message" is the message passed in from the command line. In addition to the message() function I create an error() function that formats the message the same way and sends the result to stderr.

As a bonus, this approach makes filtering updates easier. Say I want to add the date to all my output. One small edit in message() and every error and status message I send now contains a timestamp.