- /* steve jansen */
- // another day in paradise hacking code and more
- Windows Batch Scripting: Stdin, Stdout, Stderr
- File Numbers
- Redirection
- Suppressing Program Output
- Redirecting Program Output As Input to Another Program
- A Cool Party Trick
- Comments
- Guides
- Recent Posts
- Social Stuff
- Перенаправить Windows cmd stdout и stderr в один файл
- Справочная информация от MSKB
- От MSKB110930
- Перенаправление сообщений об ошибках из командной строки: STDERR / STDOUT
- Резюме
- пример
- Redirect batch stderr to file
- 6 Answers 6
- 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
/* steve jansen */
// another day in paradise hacking code and more
Windows Batch Scripting: Stdin, Stdout, Stderr
DOS, like Unix/Linux, uses the three universal “files” for keyboard input, printing text on the screen, and the printing errors on the screen. The “Standard In” file, known as stdin, contains the input to the program/script. The “Standard Out” file, known as stdout, is used to write output for display on the screen. Finally, the “Standard Err” file, known as stderr, contains any error messages for display on the screen.
File Numbers
Each of these three standard files, otherwise known as the standard streams, are referernced using the numbers 0, 1, and 2. Stdin is file 0, stdout is file 1, and stderr is file 2.
Redirection
A very common task in batch files is sending the output of a program to a log file. The > operator sends, or redirects, stdout or stderr to another file. For example, you can write a listing of the current directory to a text file:
The > operator will overwrite the contents of temp.txt with stdout from the DIR command. The >> operator is a slight variant that appends the output to a target file, rather than overwriting the target file.
A common technique is to use > to create/overwrite a log file, then use >> subsequently to append to the log file.
By default, the > and >> operators redirect stdout. You can redirect stderr by using the file number 2 in front of the operator:
You can even combine the stdout and stderr streams using the file number and the & prefix:
This is useful if you want to write both stdout and stderr to a single log file.
To use the contents of a file as the input to a program, instead of typing the input from the keyboard, use the operator.
Suppressing Program Output
The pseudofile NUL is used to discard any output from a program. Here is an example of emulating the Unix command sleep by calling ping against the loopback address. We redirect stdout to the NUL device to avoid printing the output on the command prompt screen.
Redirecting Program Output As Input to Another Program
Let’s say you want to chain together the output of one program as input to another. This is known as “piping” output to another program, and not suprisingly we use the pipe character | to get the job done. We’ll sort the output of the DIR commmand.
A Cool Party Trick
You can quickly create a new text file, say maybe a batch script, from just the command line by redirecting the command prompt’s own stdin, called CON , to a text file. When you are done typing, hit CTRL+Z , which sends the end-of-file (EOF) character.
There are a number of other special files on DOS that you can redirect, however, most are a bit dated like like LPT1 for parallel portt printers or COM1 for serial devices like modems.
Posted by Steve Jansen Mar 1 st , 2013 batch, scripting, shell, windows
Comments
Hi, I’m Steve. I’m a software developer loving life in Charlotte, NC, an (ISC) 2 CSSLP and an avid fan of Crossfit.
And, no, I’m not Steve Jansen the British jazz drummer, though that does sound like a sweet career.
Guides
Recent Posts
Social Stuff
- @steve-jansen on GitHub
- @steve-jansen on StackOverflow
- @steve-jansen ProTips on Coderwall
- @steve-jansen on Microsft Connect
- @steve-jansen on ASP.NET User Voice
- Subscribe via RSS
Copyright © 2015 — Steve Jansen — Powered by Octopress
Перенаправить Windows cmd stdout и stderr в один файл
Я пытаюсь перенаправить весь вывод (stdout + stderr) команды DOS в один файл:
Это возможно, или я должен просто перенаправить на два отдельных файла?
Синтаксис 2>&1 будет перенаправлять 2 (stderr) на 1 (stdout). Вы также можете скрыть сообщения от перенаправления NUL , более подробного объяснения и примеров по MSDN .
Ответ Андерса Линдаль является правильным, но следует отметить , что если вы перенаправлять стандартный вывод в файл и хотите , чтобы перенаправить поток ошибок, а затем вы должны убедиться , что 2>&1 указано ПОСЛЕ в 1> редирект, в противном случае он не будет работать.
Справочная информация от MSKB
Хотя принятый ответ на этот вопрос является правильным, на самом деле он мало чем объясняет, почему он работает, и, поскольку синтаксис не сразу понятен, я быстро нашел Google, чтобы выяснить, что на самом деле происходит. В надежде, что эта информация будет полезна для других, я публикую ее здесь.
От MSKB110930
Перенаправление сообщений об ошибках из командной строки: STDERR / STDOUT
Резюме
При перенаправлении вывода из приложения с помощью символа «>» сообщения об ошибках по-прежнему выводятся на экран. Это связано с тем, что сообщения об ошибках часто отправляются в поток стандартных ошибок вместо потока стандартных выходных данных.
Выходные данные консольного приложения (командной строки) или команды часто отправляются в два отдельных потока. Обычный выход отправляется на стандартный выход (STDOUT), а сообщения об ошибках отправляются на стандартную ошибку (STDERR). Когда вы перенаправляете вывод консоли, используя символ «>», вы перенаправляете только STDOUT. Чтобы перенаправить STDERR, вы должны указать «2>» для символа перенаправления. Это выбирает второй выходной поток, который является STDERR.
пример
Команда dir file.xxx (где file.xxx не существует) будет отображать следующий вывод:
Если вы перенаправите вывод на NUL устройство с помощью dir file.xxx > nul , вы все равно увидите часть сообщения об ошибке, например:
Чтобы перенаправить (только) сообщение об ошибке NUL , используйте следующую команду:
Или вы можете перенаправить вывод в одно место, а ошибки — в другое.
Вы можете распечатать ошибки и стандартный вывод в один файл, используя команду «& 1», чтобы перенаправить вывод для STDERR в STDOUT, а затем отправить вывод из STDOUT в файл:
Redirect batch stderr to file
I have a batch file that executes a java application. I’m trying to modify it so that whenever an exception occurs, it’ll write the STDERR out to a file.
It looks something like this:
Is there a way I can write the arguments %1 and %2 to the log.txt file as well? I don’t want to write it to the log file everytime this batch file gets called, only when an exception occurs.
I tried searching for a way to redirect STDERR into a variable, but I couldn’t figure it out. Ideally I’d like the log file to look something like:
6 Answers 6
Something like this might work:
javastart.cmd
I am not a java programmer myself, I cannot test this output/situation but:
1: %* means every parameters, from 1st to last (even %12 although it’s not directly available.. ) whatever the formating. Might be better to use this than delimit those. In the even of bad spacing/quoting, you would have the full parameters too. I added a line in the log, to show the full line then the parameters. You can see where the problem was if it’s a matter of bad arguments.
2: sending the stdout to null (^>nul) will only keep the stderr output, set into %%e
3: Whatever is in the do part will only happen is the for test statement actually has anything as an output, i.e. if %%e is set.
With those being said, you have to test the script and see if the exception is actually sent to stderr or, like some other softwares, to stdout even if an error occured.
I hope this helps.
The only working solution I see would be to redirect stderr to a temporary file
and afterwards looking whether something has been written to the file and writing to the log in that case.
If the batches aren’t run in sequence but rather simultaneously you need to find something to uniquify the temp variable:
This will avoid clashes between multiple running batches. However, you are currently not using anything to lock writing to your log file and things may appear out of place when other things get written to it (with other batches you might get interleaving in the echo and type commands or, when you’re redirecting output of java to that file as well, then it may get mixed up with regular output of the java program:
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