Batch / Bash: Output to STDERR

To output a message to the error stream in a batch file, simply do this:

echo your message text 1>&2

Similar syntax may be used in Bash shell scripts:

echo "your message text" 1>&2

This is useful for still outputting error messages produced by batch files or Bash scripts whose result output might be piped into a file.

For example, in the script, have lines such as

echo result output
echo syntax error: missing parameter 1>&2

then, a command such as

call script.bat > result.stdout.txt

still shows any errors on the screen (the result output is redirected into the file); conversely, the command

call script.bat 2> report.stderr.txt

redirects the errors into a file; the command

call script.bat > result.stdout.txt 2> report.stderr.txt

records the result and errors, if any, in separate files; and the command

call script.bat > combined.stdstm.txt 2>&1

combines all the output into a single file.

The special device nul in DOS (or /dev/null in Bash) may be used to throw away output. So, for example, the command

call script.bat > nul

shows the errors on the screen, but throws away the result output.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: