Wednesday, June 13

Standard output and Error output in DOS/Unix

A program outputs message. Where there is error occurred, the error message is also output to your monitor. So there are two kinds of output message:
  • Standard output, with identifier as 1
  • Error output, with identifier as 2
For example, when you dir a non existed file, you get:
If you redirect your output to a file using "dir noexist > output.txt", you get:
Now you look into the output.txt, you can see
What does that mean? That means, "File Not Found" is error message, while the "Volume in drive...." is standard output message. What you see in the 1st picture is a combination of error message (2) and standard output message(3).

Question: How to redirect both error message and standard output message in a text file?
Scenario: I have a script which is running in midnight. In some situation it doesn't work properly. I want to redirect the message, including error message and standard output message, into a text file honestly, so that I can diagnose what the problem is. Now you can see that ">" doesn't work for error message, which is the most important message in debugging.

Long story short. "dir noexist > output.txt 2>&1" will get all the information in picture (1) into output.txt. The command "2>&1" is to merge error message (which has the identifier 2) into standard output message (which has the identifier 1).

This technique is not only applied in DOS but also applied in Unix, Linux.

dir noexist 1> output.txt
Redirect the standard output message (identifier=1) to output.txt

dir noexist 2> output.txt
Redirect the error message (identifier=2) to output.txt

dir noexist 1> output.txt  2> error.txt
Redirect the standard output message (identifier=1) to output.txt , and error message (identifier=2) to error.txt

dir noexist > output.txt
Redirect the standard output message (identifier=1, which is default) to output.txt

dir noexist > output.txt 2>&1
Redirect both standard output message and error message to output.txt

NOTE: The %errorlevel% can be used to determine if a command is successfully executed or not. For example, if you dir successfully, %errorlevel%=0; otherwise, %errorlevel%=1, then you can use
IF %errorlevel% 1 GOTO errorcontrol
to take care of exception. But in my situation I only want to write down what we can see from the monitor, so I don't use it.



At May 21, 2010 4:41 PM, Anonymous Anonymous said...

THANK YOU!!! Exactly what I was looking for.


<< Home