Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way of printing out an error message

Tags:

bash

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

like image 685
Robottinosino Avatar asked Oct 03 '12 00:10

Robottinosino


People also ask

What is the word for printing error?

A mistake in anything that's printed is a misprint. You might also call it a typographical error or typo. Misprints are an embarrassment for the publisher, since they're evidence of a hasty printing job or a lack of careful proofreading.

How do I print a server error?

The print server is not connected to the network properly.Make sure that the print server and network are connected by a LAN cable properly. Make sure that the network settings for the print server are appropriate.


2 Answers

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

like image 61
sehe Avatar answered Oct 14 '22 09:10

sehe


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.

like image 23
umläute Avatar answered Oct 14 '22 09:10

umläute