xcoraw
Last Updated: February 25, 2016
·
4.276K
· mlafeldt
2190d7a468f51fa3be5eabfc9397a28b

Simple verbose mode for your shell scripts

Sometimes shell scripts are too verbose. There's too much output and constant grepping becomes a pain very soon. So you add a --quiet or --verbose option to your script, causing it to show less or more information, respectively.

At this point, you can either clutter your code with lots of if-verbose-then-else logic, or you make use of redirections as shown here:

#!/bin/sh

verbose=

case "$1" in
-v|--v|--ve|--ver|--verb|--verbo|--verbos|--verbose)
    verbose=1
    shift ;;
esac

if [ "$verbose" = 1 ]; then
    exec 4>&2 3>&1
else
    exec 4>/dev/null 3>/dev/null
fi

to_stdout() {
    echo "This goes to stdout."
}

to_stderr() {
    echo >&2 "This goes to stderr."
}

to_stdout >&3
to_stderr 2>&4
echo "Hai!"

And the same code in action:

$ sh verbose.sh
Hai!

$ sh verbose.sh --verbose
This goes to stdout.
This goes to stderr.
Hai!

$ sh verbose.sh --verbose >/dev/null
This goes to stderr.

$ sh verbose.sh --verbose 2>/dev/null
This goes to stdout.
Hai!