Writing to standard error

Writing to standard error

How to:

In Bash, you use >&2 to redirect output to stderr. Here’s a basic example:

echo "This is a normal message"
echo "This is an error message" >&2

Running this script will display both messages on the console, but if you redirect them, you can separate the stdout from the stderr. For instance:

bash script.sh > output.txt 2> error.txt

output.txt will contain "This is a normal message", while error.txt will capture "This is an error message".

For a practical use case, consider a script that processes files and reports an error if a file does not exist:


if [ ! -f "$filename" ]; then
    echo "$filename does not exist!" >&2
    exit 1
    echo "Processing $filename"

Sample output directly in the console when example.txt doesn’t exist:

example.txt does not exist!

There are no direct third-party libraries in Bash for handling stderr, as redirection is natively supported and generally sufficient. However, for complex applications, logging frameworks or external logging tools like syslog or log4bash can be incorporated to manage both stdout and stderr more effectively.