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'
else
echo 'cmd failed' >/dev/stderr
fi
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:
err(){
echo "E: $*" >>/dev/stderr
}
Now, when you have to print an error:
err "My error message"