Proper way of printing out an error message

at the beginning of my bash-scripts i usually define some functions like:

error() {
  echo "$@" 1>&2
}

fail() {
  error "$@"
  exit 1
}

which comes quite handy for outputting deadly and ordinary errors. you could move this snippet into a separate file and source that from your all of your bash-scripts with something like:

. /usr/local/lib/snippets/error_handling.sh

so whenever you decide you need a better way to deal with error messages (e.g. sending critical errors to syslog), you can do so by changing the behaviour for all scripts in one go.


On linux, I'd prefer to say

echo "Some error message" >> /dev/stderr

This will effectively do the same, of course, since /dev/stderr symlinks to /proc/$PID/fd/2

Tags:

Bash