- Redirect Output from the Windows Command Line to a Text File
- How Windows Command Prompt Output Works
- Redirect Standard Output Write to New File
- Redirect Standard Output Writes to the Same File
- Redirect Standard Error To a File
- Redirect All Output Writes to a Same File
- Silencing Standard or Error Output Streams
- Redirect Windows cmd stdout and stderr to a single file
- 7 Answers 7
- Background info from MSKB
- From MSKB110930
- Redirecting Error Messages from Command Prompt: STDERR/STDOUT
- Summary
- Example
- Suppress command line output
- 4 Answers 4
- Batch set output and error of a command to separate variables
- 3 Answers 3
Redirect Output from the Windows Command Line to a Text File
Avoid scrolling and/or save the generated output
One of the most useful ways to log and troubleshoot the behavior of commands or batch jobs that you run on Windows is to redirect output to a file.
However, there are a few different ways you can redirect command line writes to a file. The option you choose depends on how you want to view your command output.
How Windows Command Prompt Output Works
When you type a command in the Windows console (command prompt), the output from that command goes to two separate streams.
- STDOUT: Standard Out is where any standard responses from commands go. For example the standard response for the DIR command is a list of files inside a directory.
- STDERR: Standard Error is where any error messages go if there’s a problem with the command. For example if there aren’t any files in the directory, the DIR command will output “File Not Found” to the Standard Error stream.
You can redirect output to a file in Windows for both of these output streams.
Redirect Standard Output Write to New File
There are two ways you can redirect standard output of a command to a file. The first is to send the command output write to a new file every time you run the command.
To do this, open the command prompt and type:
The > character tells the console to output STDOUT to the file with the name you’ve provided.
When you run this command, you’ll notice that there isn’t any response in the command window except the error that the file doesn’t exist.
This is because the standard output for the command was redirected to a file called myoutput.txt. The file now exists in the same directory where you ran the command. The standard error output still displays as it normally does.
Note: Be careful to change the active directory for the command prompt before running the command. This way you’ll know where the output files are stored.
You can view the standard output that went to the file by typing “myoutput.txt” in the command window. This will open the text file in your default text file viewer. For most people, this is usually Notepad.exe.
The next time you run the same command, the previous output file will be deleted. A new output file will be recreated with the latest command’s output.
Redirect Standard Output Writes to the Same File
What if you don’t want to overwrite the same file? Another option is to use >> rather than > to redirect to an output file. In the case of this example, you would type:
You’ll see the same output (the error only).
But in this case, instead of overwriting the output file, this command appends the new output to the existing output file.
Every time you run a command and append the output to a file, it’ll write the new standard output to the end of the existing file.
Redirect Standard Error To a File
The same way you can redirect standard output writes to a file, you can also output the standard error stream to a file.
To do this, you’ll need to add 2> to the end of the command, followed by the output error file you want to create.
In this example, you’ll type the command:
This sends the standard output stream to myoutput.txt, and the standard error stream to output.err. The result is that no output stream at all gets displayed in the console window.
However, you can see the error messages by typing output.err. This will open the file in your default text file viewer.
As you can see, any error messages from the command are output to the error file. Just as with the standard output, you can use >> instead to append the error to errors from previously run commands.
Redirect All Output Writes to a Same File
All of the approaches above result in multiple files. One file is for the standard output stream and the other is for the standard error stream.
If you want to include both of these outputs to the same file, you can do that too. To do this, you just need to redirect all output to the same file using the following command.
Here’s how this command works:
- The standard output is directed to the output file identified by output number 1.
- The standard error output identified by the number 2 is redirected to the output file identified by number 1.
This will append the error output to the end of the standard output.
This is a useful way to see all output for any command in one file.
Silencing Standard or Error Output Streams
You can also turn off either Standard Output or Standard Error by redirecting the output to a NUL instead of a file.
Using the example above, if you only want Standard Output and no Standard Error at all, you can use the following command:
This will result in the same output file as the first example above where you only redirected the Standard Output, but with this command the error won’t echo inside the console. It won’t create an error log file either.
This is useful if you don’t care about any errors and don’t want them to become a nuisance.
You can perform any of the same output commands above from inside a BAT file and the output from that line will go to the output file you specify. This is a useful way to see whether any commands within a BAT file had any errors when they tried to run.
Ryan has been writing how-to and other technology-based articles online since 2007. He has a BSc degree in Electrical Engineering and he’s worked 13 years in automation engineering, 5 years in IT, and now is an Apps Engineer. Read Ryan’s Full Bio
Redirect Windows cmd stdout and stderr to a single file
I’m trying to redirect all output (stdout + stderr) of a DOS command to a single file:
Is it possible, or should I just redirect to two separate files?
7 Answers 7
The syntax 2>&1 will redirect 2 (stderr) to 1 (stdout). You can also hide messages by redirecting to NUL , more explanation and examples on MSDN.
Anders Lindahl’s answer is correct, but it should be noted that if you are redirecting stdout to a file and want to redirect stderr as well then you MUST ensure that 2>&1 is specified AFTER the 1> redirect, otherwise it will not work.
Background info from MSKB
While the accepted answer to this question is correct, it really doesn’t do much to explain why it works, and since the syntax is not immediately clear I did a quick google to find out what was actually going on. In the hopes that this information is helpful to others, I’m posting it here.
From MSKB110930
Redirecting Error Messages from Command Prompt: STDERR/STDOUT
Summary
When redirecting output from an application using the ‘>’ symbol, error messages still print to the screen. This is because error messages are often sent to the Standard Error stream instead of the Standard Out stream.
Output from a console (Command Prompt) application or command is often sent to two separate streams. The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the «>» symbol, you are only redirecting STDOUT. In order to redirect STDERR you have to specify ‘2>’ for the redirection symbol. This selects the second output stream which is STDERR.
Example
The command dir file.xxx (where file.xxx does not exist) will display the following output:
If you redirect the output to the NUL device using dir file.xxx > nul , you will still see the error message part of the output, like this:
To redirect (only) the error message to NUL , use the following command:
Or, you can redirect the output to one place, and the errors to another.
You can print the errors and standard output to a single file by using the «&1» command to redirect the output for STDERR to STDOUT and then sending the output from STDOUT to a file:
Suppress command line output
I have a simple batch file like this:
If «test.exe» is not running, I get this message:
Why does this error message get displayed, even though I have redirected output to NUL?
How can I suppress that output?
4 Answers 4
Because error messages often go to stderr not stdout .
Change the invocation to this:
and all will be better.
That works because stdout is file descriptor 1, and stderr is file descriptor 2 by convention. (0 is stdin , incidentally.) The 2>&1 copies output file descriptor 2 from the new value of 1, which was just redirected to the null device.
This syntax is (loosely) borrowed from many Unix shells, but you do have to be careful because there are subtle differences between the shell syntax and CMD.EXE.
Update: I know the OP understands the special nature of the «file» named NUL I’m writing to here, but a commenter didn’t and so let me digress with a little more detail on that aspect.
Going all the way back to the earliest releases of MSDOS, certain file names were preempted by the file system kernel and used to refer to devices. The earliest list of those names included NUL , PRN , CON , AUX and COM1 through COM4 . NUL is the null device. It can always be opened for either reading or writing, any amount can be written on it, and reads always succeed but return no data. The others include the parallel printer port, the console, and up to four serial ports. As of MSDOS 5, there were several more reserved names, but the basic convention was very well established.
When Windows was created, it started life as a fairly thin application switching layer on top of the MSDOS kernel, and thus had the same file name restrictions. When Windows NT was created as a true operating system in its own right, names like NUL and COM1 were too widely assumed to work to permit their elimination. However, the idea that new devices would always get names that would block future user of those names for actual files is obviously unreasonable.
Windows NT and all versions that follow (2K, XP, 7, and now 8) all follow use the much more elaborate NT Namespace from kernel code and to carefully constructed and highly non-portable user space code. In that name space, device drivers are visible through the \Device folder. To support the required backward compatibility there is a special mechanism using the \DosDevices folder that implements the list of reserved file names in any file system folder. User code can brows this internal name space using an API layer below the usual Win32 API; a good tool to explore the kernel namespace is WinObj from the SysInternals group at Microsoft.
For a complete description of the rules surrounding legal names of files (and devices) in Windows, this page at MSDN will be both informative and daunting. The rules are a lot more complicated than they ought to be, and it is actually impossible to answer some simple questions such as «how long is the longest legal fully qualified path name?».
Batch set output and error of a command to separate variables
In windows 7 batch (cmd.exe command-line), I am trying to redirect the standard output (stdout) and standard error (stderr) of a command to separate variables (so the 1st variables is set to the output, and the 2nd variable is set to the error (if any)) without using any temporary files. I have tried and tried with no success at this.
So, what would be a working way to set the output and error of a command to separate variables?
3 Answers 3
You could go for two nested for /F loops, where the inner one captures the standard output and the outer one captures the redirected error. Since the inner one instances a new cmd process, the captured text cannot just be assigned to a variable, because it will be lost after execution finishes. Rather I precede every line with | and just echo it to the standard output. The outer loop detects the leading | and separates the lines accordingly:
The following restrictions apply to the code:
- empty lines are ignored;
- lines that begin with a semicolon ; are ignored;
- exclamation marks ! are lost, because delayed environment variable expansion is enabled;
- lines that begin with a pipe character | may be assigned wrongly;
- the overall size of data must not exceed 8190 bytes;
All of those limitations are true for both standard output and standard error.
Here is an improved variant of the above code. The issues concerning empty lines and lines beginning with a semicolon ; are resolved, the other restrictions still remain:
The findstr command is used to precede every single line with a line number plus : , so no line appears empty to for /F ; this prefix is removed later on, of course. This change also solves the ; issue implicitly.
Because of the nested piping into findstr , multiple escaping is required to hide the | character as long as its piping function is actually needed.
First off, batch does not have a simple method to capture multi-line output like unix shell scripting. You can use FOR /F to build a multi-line value line by line, but the total length is limited to : . The FINDSTR prefixes each line with a line number followed by a : , and the FOR /F parses out the line number to be used as an «array» index, as well as the value after the : .
2nd Edit
Additional code is required if you want to properly handle output that begins with : .
Below I have adapted aschipfl’s 2nd code that avoids using a temp file so that it preserves ! characters. The code just gets uglier and uglier 😉
It is a bit simpler if the result is stored in arrays instead of a pair of strings.
I know many people try to avoid temp files, but in this case I think it is counter productive. Tests have shown that temp files can be much faster than processing the result of a command with a FOR /F loop when the output is very large. And the temp file solution is so much simpler. So I would definitely use the temp file solution.
But finding a non-temp file solution is an interesting challenge. Kudos to aschipfl for working out the complicated escape sequences.
3rd (final?) Edit
At last, here is a solution that eliminates all restrictions, other than each captured line of output must be less than around 8180 bytes.
I could have put the entire code in one big loop, but then the escape sequences would have been a nightmare. Figuring out the escape sequences is much simpler when I break the code into smaller subroutines.
I capture the stdout and stderr for a bunch of ECHO commands found in the :test routine at the bottom.
I still like the temp file solution much better 😉