Print error messages to stderr

suggest change

Error messages are generally included in a script for debugging purposes or for providing rich user experience. Simply writing error message like this:

cmd || echo 'cmd failed'

may work for simple cases but it’s not the usual way. In this example, the error message will pollute the actual output of the script by mixing both errors and successful output in stdout.

In short, error message should go to stderr not stdout. It’s pretty simple:

cmd || echo 'cmd failed' >/dev/stderr

Another example:

if cmd; then
    echo 'success'
    echo 'cmd failed' >/dev/stderr

In the above example, the success message will be printed on stdout while the error message will be printed on stderr.

A better way to print error message is to define a function:

    echo "E: $*" >>/dev/stderr

Now, when you have to print an error:

err "My error message"

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents