Robottinosino
Robottinosino

Reputation: 10882

Proper way of printing out an error message

Is this line the best way to print out an error message in Bash?

echo 'Error: banana' >&2

I need to update tens of Bash scripts which use all different ways of logging errors and I might as well choose the "right" way to do this and adhere to a standard as I do it...

Upvotes: 15

Views: 22064

Answers (2)

umläute
umläute

Reputation: 31284

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.

Upvotes: 17

sehe
sehe

Reputation: 392931

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

Upvotes: 10

Related Questions