To distinguish between normal output messages and error messages, sometimes there is a need to write messages to the stderr
stream from a shell script. By default, output messages are written to stdout
stream only.
To write or echo to stderr
, I normally use a custom function that redirects the output of the echo
command to the standard error stream.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#!/bin/sh # call this function to write to stderr echo_stderr () { echo "$@" >&2 } # write to stdout echo this is stdout #write to stderr echo_stderr this is stderr |
The above script has a custom function called echo_stderr
that performs the stderr
redirect.
Let’s name the above script as stderr.sh
. Based on the script, if you want to filter out stderr
messages, perform a redirect like this.
1 2 |
$ stderr.sh 2>/dev/null this is stdout |
To filter out stdout
messages, perform a similar redirection, but this time by redirecting the stdout
stream to the null device.
1 2 |
$ stderr.sh 1>/dev/null this is stderr |