Redirect error output cmd

Display & Redirect Output On this page I’ll try to explain how redirection works. To illustrate my story there are some examples you can try for yourself. For an overview of redirection and piping, view my original redirection page. Display text To display a text on screen we have the ECHO command: This will […]

Содержание

  1. Display & Redirect Output
  2. Display text
  3. Streams
  4. Redirection
  5. Redirect «all» output to a single file:
  6. Redirect errors to a separate error log file:
  7. Escaping Redirection (not to be interpreted as «Avoiding Redirection»)
  8. Redirecting error messages from Command Prompt: STDERR/STDOUT
  9. Summary
  10. Example
  11. Rushi’s
  12. Java, Js and everything web
  13. Windows Command Prompt Redirecting STDOUT/STDERR
  14. I/O Redirection and Pipes

Display & Redirect Output

On this page I’ll try to explain how redirection works.
To illustrate my story there are some examples you can try for yourself.

For an overview of redirection and piping, view my original redirection page.

Display text

To display a text on screen we have the ECHO command:

This will show the following text on screen:

When I say «on screen», I’m actually referring to the «DOS Prompt», «console» or «command window», or whatever other «alias» is used.

Streams

The output we see in this window may all look alike, but it can actually be the result of 3 different «streams» of text, 3 «processes» that each send their text to thee same window.

Those of you familiar with one of the Unix/Linux shells probably know what these streams are:

  • Standard Output
  • Standard Error
  • Console

Standard Output is the stream where all, well, standard output of commands is being sent to.
The ECHO command sends all its output to Standard Output.

Standard Error is the stream where many (but not all) commands send their error messages.

And some, not many, commands send their output to the screen bypassing Standard Output and Standard Error, they use the Console. By definition Console isn’t a stream.

There is another stream, Standard Input: many commands accept input at their Standard Input instead of directly from the keyboard.
Probably the most familiar example is MORE :

where the MORE command accepts DIR ‘s Standard Output at its own Standard Input, chops the stream in blocks of 25 lines (or whatever screen size you may use) and sends it to its own Standard Output.

(Since MORE ‘s Standard Input is used by DIR , MORE must catch its keyboard presses (the «Any Key») directly from the keyboard buffer instead of from Standard Input.)

Redirection

You may be familiar with «redirection to NUL» to hide command output:

will show nothing on screen.
That’s because >NUL redirects all Standard Output to the NUL device, which does nothing but discard it.

Now try this (note the typo):

The result may differ for different operating system versions, but in Windows XP I get the following error message:

This is a fine demonstration of only Standard Output being redirected to the NUL device, but Standard Error still being displayed.

Redirecting Standard Error in «true» MS-DOS (COMMAND.COM) isn’t possible (actually it is, by using the CTTY command, but that would redirect all output including Console, and input, including keyboard).
In Windows NT 4 and later (CMD.EXE) and in OS/2 (also CMD.EXE) Standard Error can be redirected by using 2> instead of >

A short demonstration. Try this command:

What you should get is:

You see? The same result you got with ECHO Hello world without the redirection.
That’s because we redirected the Standard Error stream to the NUL device, but the ECHO command sent its output to the Standard Output stream, which was not redirected.

Now make a typo again:

What did you get? Nothing
That’s because the error message was sent to the Standard Error stream, which was in turn redirected to the NUL device by 2>NUL

When we use > to redirect Standard Output, CMD.EXE interprets this as 1> , as can be seen by writing and running this one-line batch file «test.bat»:

Now run test.bat in CMD.EXE and watch the result:

It looks like CMD.EXE uses 1 for Standard Output and 2 for Standard Error. We’ll see how we can use this later.

Ok, now that we get the idea of this concept of «streams», let’s play with it.
Copy the following code into Notepad and save it as «test.bat»:

Run test.bat in CMD.EXE, and this is what you’ll get:

Now let’s see if we can separate the streams again.
Run:

and you should see:

We redirected Standard Output to the NUL device, and what was left were Standard Error and Console.

and you should see:

We redirected Standard Error to the NUL device, and what was left were Standard Output and Console.

Nothing new so far. But the next one is new:

and you should see:

This time we redirected both Standard Output and Standard Error to the NUL device, and what was left was only Console.
It is said Console cannot be redirected, and I believe that’s true. I can assure you I did try!

In this case, we could also have used test.bat >NUL 2>NUL
This redirects Standard Output to the NUL device and Standard Error to the same NUL device.
With the NUL device that’s no problem, but when redirecting to a file one of the redirections will lock the file for the other redirection.
What 2>&1 does, is merge Standard Error into the Standard Output stream, so Standard output and Standard Error will continue as a single stream.

Redirect «all» output to a single file:

and you’ll get this text on screen (we’ll never get rid of this line on screen, as it is sent to the Console and cannot be redirected):

You should also get a file named test.txt with the following content:

Note: The commands
test.bat > test.txt 2>&1
test.bat 1> test.txt 2>&1
test.bat 2> test.txt 1>&2
all give identical results.

Redirect errors to a separate error log file:

and you’ll get this text on screen (we’ll never get rid of this line on screen, as it is sent to the Console and cannot be redirected):

You should also get a file named testlog.txt with the following content:

and another file named testerrors.txt with the following content:

Nothing is impossible, not even redirecting the Console output.

Unfortunately, it can be done only in the old MS-DOS versions that came with a CTTY command.

The general idea was this:

A pause or prompt for input before the CTTY CON command meant one had to press the reset button!

Besides being used for redirection to the NUL device, with CTTY COM1 the control could be passed on to a terminal on serial port COM1.

Escaping Redirection (not to be interpreted as «Avoiding Redirection»)

Redirection always uses the main or first command’s streams:

will redirect START ‘s Standard Output to logfile , not command ‘s!
The result will be an empty logfile .

A workaround that may look a bit intimidating is grouping the command line and escaping the redirection:

What this does is turn the part between parentheses into a «literal» (uninterpreted) string that is passed to the command interpreter of the newly started process, which then in turn does interpret it.
So the interpretation of the parenthesis and redirection is delayed, or deferred.

Note: Be careful when using workarounds like these, they may be broken in future (or even past) Windows versions.

A safer way to redirect START ed commands’ output would be to create and run a «wrapper» batch file that handles the redirection.
The batch file would look like this:

Источник

Redirecting error messages from Command Prompt: STDERR/STDOUT

This article describes redirecting error messages from Command Prompt.

Original product version: В Visual C++
Original KB number: В 110930

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 that is STDERR.

Example

The command dir file.xxx (where file.xxx does not exist) will display the following output:

Volume in drive F is Candy Cane Volume Serial Number is 34EC-0876
File Not Found

If you redirect the output to the NUL device using dir file.xxx > nul , you will still see the error message:

To redirect 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:

Источник

Rushi’s

Java, Js and everything web

Windows Command Prompt Redirecting STDOUT/STDERR

The ‘>’ operator is used to redirect the output to a new file, the ‘>>’ is used to redirect the output and append to the file.
Now both the STDOUT and STDERR are written to the console by default. 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.

For Example, running the dir command on a file gives both stdout and stderr like below:

C: dir nosuchfile.txt Volume in drive C has no label. Volume Serial Number is B8A1-5FD1Directory of C:File Not Found

Here the “File Not Found” message is the STDERR and the rest was for STDOUT. Now if you want to redirect the whole output to a file, just running the command dir nosuchfile.txt > result.log will not cut it. You need to do one of the following:

Sending the STDERR and STDOUT to different files:

dir nosuchfile.txt > out.log 2>error.log

Sending the STDERR and STDOUT to Same file:

Источник

I/O Redirection and Pipes

Normally, any output from a console program appears in the Command Prompt window, but you can redirect it into a file using the > character. For example, the command

generates the same listing as the previous example but stores it in a file named tasks.txt. Command-line programs send their output to what is called the standard output stream. By default, anything the program sends to the standard output is printed in the Command Prompt window. Figure below shows how this looks. The first tasklist command in the figure sends its output to the Command Prompt window. The second tasklist command has its output redirected into a file.

Some programs read input through a standard input stream. By default, this is connected to your keyboard, and whatever you type is read by the program. For example, the sort command reads lines of text from the standard input, sorts them alphabetically, and writes the results to the standard output. If you type the following lines at the command prompt,

sort spits out the lines in order: a, b, c. (Note that Ctrl+Z on a line by itself indicates the end of input.) You can redirect the standard input with the sort

tells sort to read input from the file somefile.txt.You can use both input and output redirection at the same time.The command

rearranges the contents of somefile.txt and creates a new file named

You can also specify that the output isn’t to replace an existing file but rather should simply be stuck onto the end (that is, appended ) with the characters >>, as in this example:

dir /b c: >listing.txt
dir /b d: >>listing.txt

The first command creates the file listing.txt, and the second appends its output onto the end of listing.txt. (If the file listing.txt doesn’t already exist, don’t worry: >> creates it.)

Finally, you can hook the output of one program directly to the input of another by using the vertical bar symbol (|), usually found above the backslash () on a keyboard. For example, the find command reads lines from the input and passes only lines containing a designated string.The command

tasklist | find «winword»

has tasklist send its list of all programs through find which types out only the line or lines containing «winword.» Finally,

tasklist | find «winword» >tasks.txt

connects tasklist to find, and find to a file.

Input and output redirection let you connect programs and files as if you are making plumbing connections.The | symbol is often called a pipe for this reason, and programs such as find are often called filters.

Note One handy filter to know about is more, a program that passes whatever it’s given as input to its output. What makes more useful is that it pauses after printing a screen full of text. more lets you view long listings that would otherwise scroll off the screen too quickly to read. For example, the command

helps you see the entire list of programs. When you see the prompt — More — at the bottom of the screen, press the spacebar to view the next screen full.

The standard error is another output stream available to console programs. By default, if a program writes information to the standard error stream, the text appears in the Command Prompt window. Programs usually use this to display important error messages that they want you to see, even if the standard output is redirected to a file or pipe.You can redirect standard error too, though, if you want to capture the error messages in a file.

If you’ve worked with DOS, Linux, or Unix, this is probably already familiar to you. However, there are several input redirection variations you might not be familiar with. Table below lists all the redirection instructions that CMD recognizes.

Input and Output Redirection

Redirection Option Action
file Writes standard output to file.
>>file Appends standard output to file.
1>file Writes standard output to file.*
1>>file Appends standard output to file.
2>file Writes standard error to file.
2>>file Appends standard error to file.
2>&1 Directs standard error through the same stream as standard output. Both can then be redirected to a file or piped to another program.
nextcommand Sends output to the input of nextcommand.

* The number 1 refers to the standard output stream and the number 2 to the standard error stream.

Two special forms of output redirection are output to the NUL device and output to a printer.Windows recognizes the special filename nul in any folder on any drive and treats it as a «black hole» file. If you issue a command and redirect its output to nul, the output is discarded.This type of direction is useful in batch files when you want a command to do something, but don’t want or need the user to see any error messages it might print. For example,

net use f: /del >nul 2>nul

runs the net use command and makes sure that no output appears to the user.

Special filenames LPT1, LPT2, and so on, represent your default printer and your local printer connected to ports LPT1, LPT2, and so on.You can direct the output of a command to the printer using redirection to these names.You can also direct output to network-connected printers by mapping these devices to network printers using the net use command. Special name PRN is the same as LPT1.

In practical day-to-day use, standard output redirection lets you capture the output of a console program into a file, where you can edit or incorporate it into your documents. Standard error redirection is handy when you need to gather hardcopy evidence from a program that is printing error messages. Input redirection is used most often in a batch file setting, where you want to have a command run automatically from input prepared ahead of time.

Here are some examples:

This has the CMD command-line shell print its built-in help information, and it passes the text through more so it can be read a page at a time.

cmd /? > cmd.info
notepad cmd.info

This has CMD print its help information again, but this time, the text is stored in a file, and you view the file with Notepad. (Window-based programs can be useful on occasion.)

Источник

Rob van der Woude's Scripting Pages

Display & Redirect Output

On this page I’ll try to explain how redirection works.
To illustrate my story there are some examples you can try for yourself.

For an overview of redirection and piping, view my original redirection page.

Display text

To display a text on screen we have the ECHO command:

ECHO Hello world

This will show the following text on screen:

Hello world

When I say «on screen», I’m actually referring to the «DOS Prompt», «console» or «command window», or whatever other «alias» is used.

Streams

The output we see in this window may all look alike, but it can actually be the result of 3 different «streams» of text, 3 «processes» that each send their text to thee same window.

Those of you familiar with one of the Unix/Linux shells probably know what these streams are:

  • Standard Output
  • Standard Error
  • Console

Standard Output is the stream where all, well, standard output of commands is being sent to.
The ECHO command sends all its output to Standard Output.

Standard Error is the stream where many (but not all) commands send their error messages.

And some, not many, commands send their output to the screen bypassing Standard Output and Standard Error, they use the Console.
By definition Console isn’t a stream.

There is another stream, Standard Input: many commands accept input at their Standard Input instead of directly from the keyboard.
Probably the most familiar example is MORE:

DIR /S | MORE

where the MORE command accepts DIR‘s Standard Output at its own Standard Input, chops the stream in blocks of 25 lines (or whatever screen size you may use) and sends it to its own Standard Output.

(Since MORE‘s Standard Input is used by DIR, MORE must catch its keyboard presses (the «Any Key») directly from the keyboard buffer instead of from Standard Input.)

Redirection

You may be familiar with «redirection to NUL» to hide command output:

ECHO Hello world>NUL

will show nothing on screen.
That’s because >NUL redirects all Standard Output to the NUL device, which does nothing but discard it.

Now try this (note the typo):

EHCO Hello world>NUL

The result may differ for different operating system versions, but in Windows XP I get the following error message:

'EHCO' is not recognized as an internal or external command, operable program or batch file.

This is a fine demonstration of only Standard Output being redirected to the NUL device, but Standard Error still being displayed.

Redirecting Standard Error in «true» MS-DOS (COMMAND.COM) isn’t possible (actually it is, by using the CTTY command, but that would redirect all output including Console, and input, including keyboard).
In Windows NT 4 and later (CMD.EXE) and in OS/2 (also CMD.EXE) Standard Error can be redirected by using 2> instead of >

A short demonstration. Try this command:

ECHO Hello world 2>NUL

What you should get is:

Hello world

You see? The same result you got with ECHO Hello world without the redirection.
That’s because we redirected the Standard Error stream to the NUL device, but the ECHO command sent its output to the Standard Output stream, which was not redirected.

Now make a typo again:

EHCO Hello world 2>NUL

What did you get?
Nothing
That’s because the error message was sent to the Standard Error stream, which was in turn redirected to the NUL device by 2>NUL

When we use > to redirect Standard Output, CMD.EXE interprets this as 1>, as can be seen by writing and running this one-line batch file «test.bat»:

DIR > NUL

Now run test.bat in CMD.EXE and watch the result:

C:>test.bat

C:>DIR  1>NUL

C:>_

It looks like CMD.EXE uses 1 for Standard Output and 2 for Standard Error.
We’ll see how we can use this later.

Ok, now that we get the idea of this concept of «streams», let’s play with it.
Copy the following code into Notepad and save it as «test.bat»:

@ECHO OFF
ECHO This text goes to Standard Output
ECHO This text goes to Standard Error 1>&2
ECHO This text goes to the Console>CON

Run test.bat in CMD.EXE, and this is what you’ll get:

C:>test.bat
This text goes to Standard Output
This text goes to Standard Error
This text goes to the Console

C:>_

Now let’s see if we can separate the streams again.
Run:

test.bat > NUL

and you should see:

C:>test.bat
This text goes to Standard Error
This text goes to the Console

C:>_

We redirected Standard Output to the NUL device, and what was left were Standard Error and Console.

Next, run:

test.bat 2> NUL

and you should see:

C:>test.bat
This text goes to Standard Output
This text goes to the Console

C:>_

We redirected Standard Error to the NUL device, and what was left were Standard Output and Console.

Nothing new so far. But the next one is new:

test.bat > NUL 2>&1

and you should see:

C:>test.bat
This text goes to the Console

C:>_

This time we redirected both Standard Output and Standard Error to the NUL device, and what was left was only Console.
It is said Console cannot be redirected, and I believe that’s true.
I can assure you I did try!

To get rid of screen output sent directly to the Console, either run the program in a separate window (using the START command), or clear the screen immediately afterwards (CLS).

In this case, we could also have used test.bat >NUL 2>NUL
This redirects Standard Output to the NUL device and Standard Error to the same NUL device.
With the NUL device that’s no problem, but when redirecting to a file one of the redirections will lock the file for the other redirection.
What 2>&1 does, is merge Standard Error into the Standard Output stream, so Standard output and Standard Error will continue as a single stream.

Redirect «all» output to a single file:

Run:

test.bat > test.txt 2>&1

and you’ll get this text on screen (we’ll never get rid of this line on screen, as it is sent to the Console and cannot be redirected):

This text goes to the Console

You should also get a file named test.txt with the following content:

This text goes to Standard Output
This text goes to Standard Error
Note: The commands
test.bat  > test.txt 2>&1
test.bat 1> test.txt 2>&1
test.bat 2> test.txt 1>&2
all give identical results.

Redirect errors to a separate error log file:

Run:

test.bat > testlog.txt 2> testerrors.txt

and you’ll get this text on screen (we’ll never get rid of this line on screen, as it is sent to the Console and cannot be redirected):

This text goes to the Console

You should also get a file named testlog.txt with the following content:

This text goes to Standard Output

and another file named testerrors.txt with the following content:

This text goes to Standard Error

Nothing is impossible, not even redirecting the Console output.

Unfortunately, it can be done only in the old MS-DOS versions that came with a CTTY command.

The general idea was this:

CTTY NUL
ECHO Echo whatever you want, it won't be displayed on screen no matter what.
ECHO By the way, did I warn you that the keyboard doesn't work either?
ECHO I suppose that's why CTTY is no longer available on Windows systems.
ECHO The only way to get control over the computer again is a cold reboot,
ECHO or the following command:
CTTY CON

A pause or prompt for input before the CTTY CON command meant one had to press the reset button!

Besides being used for redirection to the NUL device, with CTTY COM1 the control could be passed on to a terminal on serial port COM1.

Escaping Redirection (not to be interpreted as «Avoiding Redirection»)

Redirection always uses the main or first command’s streams:

START command > logfile

will redirect START‘s Standard Output to logfile, not command‘s!
The result will be an empty logfile.

A workaround that may look a bit intimidating is grouping the command line and escaping the redirection:

START CMD.EXE /C ^(command ^> logfile^)

What this does is turn the part between parentheses into a «literal» (uninterpreted) string that is passed to the command interpreter of the newly started process, which then in turn does interpret it.
So the interpretation of the parenthesis and redirection is delayed, or deferred.

Note: Be careful when using workarounds like these, they may be broken in future (or even past) Windows versions.

A safer way to redirect STARTed commands’ output would be to create and run a «wrapper» batch file that handles the redirection.
The batch file would look like this:

command > logfile

and the command line would be:

START batchfile

Some «best practices» when using redirection in batch files:

  • Use >filename.txt 2>&1 to merge Standard Output and Standard Error and redirect them together to a single file.
    Make sure you place the redirection «commands» in this order.
  • Use >logfile.txt 2>errorlog.txt to redirect success and error messages to separate log files.
  • Use >CON to send text to the screen, no matter what, even if the batch file’s output is redirected.
    This could be useful when prompting for input even if the batch file’s output is being redirected to a file.
  • Use 1>&2 to send text to Standard Error.
    This can be useful for error messages.
  • It’s ok to use spaces in redirection commands.
    Note however, that a space between an ECHO command and a > will be redirected too.
    DIR>filename.txt and DIR > filename.txt are identical, ECHO Hello world>filename.txt and ECHO Hello world > filename.txt are not, even though they are both valid.
    It is not ok to use spaces in >> or 2> or 2>&1 or 1>&2 (before or after is ok).
  • In Windows NT 4, early Windows 2000 versions, and OS/2 there used to be some ambiguity with ECHOed lines ending with a 1 or 2, immediately followed by a >:
    ECHO Hello world2>file.txt would result in an empty file file.txt and the text Hello world (without the trailing «2») on screen (CMD.EXE would interpret it as ECHO Hello world 2>file.txt).
    In Windows XP the result is no text on screen and file.txt containing the line Hello world2, including the trailing «2» (CMD.EXE interprets it as ECHO Hello world2 >file.txt).
    To prevent this ambiguity, either use parentheses or insert an extra space yourself:
    ECHO Hello World2 >file.txt
    (ECHO Hello World2)>file.txt
  • «Merging» Standard Output and Standard Error with 2>&1 can also be used to pipe a command’s output to another command’s Standard Input:
    somecommand 2>&1 | someothercommand
  • Redirection overview page
  • Use the TEE command to display on screen and simultaneously redirect to file

page last modified: 2016-09-19

Перенаправление ввода-вывода в cmd

Перенаправление стандартных ввода-вывода и ошибок

С помощью переназначения устройств ввода/вывода одна программа может направить свой вывод на вход другой или перехватить вывод другой программы, используя его в качестве своих входных данных. Таким образом, имеется возможность передавать информацию от процесса к процессу при минимальных программных издержках. Практически это означает, что для программ, которые используют стандартные входные и выходные устройства, операционная система позволяет:

  • выводить сообщения программ не на экран (стандартный выходной поток), а в файл или на принтер (перенаправление вывода);
  • читать входные данные не с клавиатуры (стандартный входной поток), а из заранее подготовленного файла (перенаправление ввода);
  • передавать сообщения, выводимые одной программой, в качестве входных данных для другой программы (конвейеризация или композиция команд).

Из командной строки эти возможности реализуются следующим образом. Для того, чтобы перенаправить текстовые сообщения, выводимые какой-либо командой из командной строки, в текстовый файл, нужно использовать конструкцию команда > имя_файла. Если при этом заданный для вывода файл уже существовал, то он перезаписывается (старое содержимое теряется), если не существовал создается. Можно также не создавать файл заново, а дописывать информацию, выводимую командой, в конец существующего файла. Для этого команда перенаправления вывода должна быть задана так: команда >> имя_файла. С помощью символа < можно прочитать входные данные для заданной команды не с клавиатуры, а из определенного (заранее подготовленного) файла: команда < имя_файла

Примеры перенаправления ввода/вывода в командной строке

Приведем несколько примеров перенаправления ввода/вывода.

1. Вывод результатов команды ping в файл  ping ya.ru > ping.txt

2. Добавление текста справки для команды XCOPY в файл copy.txt: XCOPY /? >> copy.txt

В случае необходимости сообщения об ошибках (стандартный поток ошибок) можно перенаправить в текстовый файл с помощью конструкции команда 2> имя_файла В этом случае стандартный вывод будет производиться на экран. Также имеется возможность информационные сообщения и сообщения об ошибках выводить в один и тот же файл. Делается это следующим образом: команда > имя_файла 2>&1

Например, в приведенной ниже команде стандартный выходной поток и стандартный поток ошибок перенаправляются в файл copy.txt: XCOPY A:1.txt C: > copy.txt 2>&1

  1. Redirection Operator in Batch Script
  2. Redirect Output Using the Redirection Operator in Batch Script
  3. Redirect the Output to a Text File by Calling a Subroutine From Within a Batch File

Redirect Output to a Text File From Within a Batch File

This tutorial will teach the different ways of redirecting the output from within a text file.

Redirection Operator in Batch Script

We can redirect the output of a batch file to a text file using the redirection operator. A redirection operator redirects the input to the command or output from the command.

When running a Batch file, the command is executed in cmd.exe. The output of these commands is obtained in two streams, i.e., standard output and standard error.

These outputs can be either redirected to separate files or a single file.

A redirection operator is denoted by >. By default, the cmd uses > for the standard output, the same as 1>.

However, it uses 2> for the standard error. The basic syntax of a redirection operator is given below.

Redirecting output to a text file can be very useful. When there’s a very long range of output or a command is executed in an interval of time, the data must be saved.

Also, if an error occurs while running a Batch file, it quickly disappears with a blank console screen. In all cases, the output and the error can be redirected to a text file.

When using a Batch file, it is better to redirect the output from within the Batch file. So, whenever you run it by double-clicking on it, it will redirect the output, which is better than doing it manually every time from the command line.

Redirect Output Using the Redirection Operator in Batch Script

We can redirect the standard output of the entire Batch file or just a part of it. Also, the standard output and standard error can be saved in a single file or separate files.

Redirect the Standard Output to a Text File From Within a Batch File

To redirect the standard output to a text file, add the redirection operator between the command and the text file, as shown in the syntax below.

For example, we have to redirect the output of the command powercfg to a text file named stdoutput.txt. The following command will create a new file called stdoutput.txt.

If the file already exists, it will be overwritten.

echo "The output will be redirected to a text file"
powercfg /a > stdoutput.txt

testfile redirection

Output:

output redirection

The > operator overwrites the existing file with the new output when you run the Batch file. To keep the old output and append the new output, use >> instead of > to append the output to the same text file.

echo "The output will be redirected to a text file"
powercfg /a >> stdoutput.txt

testfile append

Output:

output append

Redirect Standard Output and Standard Error to a Separate Text File From Within a Batch File

To redirect the standard output (stdout) and standard error (stderr) to separate text files, use 1> for standard output and 2> for standard error, as shown below.

@echo off
echo "The output will be redirected to stdoutput.txt"
powercfg /a 1> stdoutput.txt
echo "The errors will be redirected to stderror.txt"
powercfg /energy 2> stderror.txt

testfile redirect to separate files

Standard output:

output stdoutput

Standard error:

output stderror

Redirect All Outputs to a Single File From Within a Batch File

We can save the standard output and standard error in a single file using 2>&1 after the file name.

The syntax for this is shown below:

@echo off
echo "The output will be redirected to stdoutput.txt"
powercfg /a > stdoutput.txt 2>&1

testfile redirect to a single file

Output:

output redirect to a single file

Similarly, to append both the outputs to a single file, use >> instead of > in the above command.

ifconfig >> output.txt 2>&1

testfile append redirect to a single file

The output will be the same as there are no errors in the file.

Redirect the Output to a Text File by Calling a Subroutine From Within a Batch File

Another way to redirect the output of a Batch file to a text file is by using the call and sub commands. An example of calling a labeled subroutine is given below.

@echo off
call:sub_ipconfig > ipconfig.txt
call:sub_powercfg > powercfg.txt

GOTO: END

:sub_ipconfig
ipconfig
EXIT /B

:sub_powercfg
powercfg /a
EXIT /B

:END

testfile call sub

Output- ipconfig.txt:

output call sub ipconfig

Output- powercfg.txt:

output call sub powercfg

Here, the call command is used to call the subroutine as labeled. First, the subroutine sub_ipconfig is called, and the output is redirected to a file named ipconfig.txt.

Then the second subroutine sub_powercfg is called, and the output is redirected to a file named powercfg.txt. The command exit /B stops the execution after this line and continues running the main program.

If we use exit instead of exit /b, it will stop the execution of the Batch file.

So, we have discussed two different ways to redirect the output within a Batch file.

  • Overview
  • Part 1 – Getting Started
  • Part 2 – Variables
  • Part 3 – Return Codes
  • Part 4 – stdin, stdout, stderr
  • Part 5 – If/Then Conditionals
  • Part 6 – Loops
  • Part 7 – Functions
  • Part 8 – Parsing Input
  • Part 9 – Logging
  • Part 10 – Advanced Tricks

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:

DIR > temp.txt

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.

SomeCommand.exe   > temp.txt
OtherCommand.exe >> temp.txt

By default, the > and >> operators redirect stdout. You can redirect stderr by using the file number 2 in front of the
operator:

DIR SomeFile.txt  2>> error.txt

You can even combine the stdout and stderr streams using the file number and the & prefix:

DIR SomeFile.txt 2>&1

This is useful if you want to write both stdout and stderr to a single log file.

DIR SomeFile.txt > output.txt 2>&1

To use the contents of a file as the input to a program, instead of typing the input from the keyboard, use the < operator.

SORT < SomeFile.txt

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.

PING 127.0.0.1 > NUL

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.

DIR /B | SORT

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.

TYPE CON > output.txt

Screenshot of sending keyboard input to a file

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.


<< Part 3 – Return Codes


Part 5 – If/Then Conditionals >>

Windows 7 / Getting Started


Normally, any output from a console program appears in the Command Prompt window,
but you can redirect it into a file using the > character. For example, the command

tasklist >tasks.txt

generates the same listing as the previous example but stores it in a file named
tasks.txt. Command-line programs send their output to what is called the standard
output stream. By default, anything the program sends to the standard output is printed
in the Command Prompt window. Figure below shows how this looks. The first tasklist command in the figure sends its output to the Command Prompt window.
The second tasklist command has its output redirected into a file.

Tasklist Command

Some programs read input through a standard input stream. By default, this is connected
to your keyboard, and whatever you type is read by the program. For example,
the sort command reads lines of text from the standard input, sorts them alphabetically,
and writes the results to the standard output. If you type the following lines at the command prompt,

sort
c
b
a
Ctrl+Z

sort spits out the lines in order: a, b, c. (Note that Ctrl+Z on a line by itself indicates
the end of input.) You can redirect the standard input with the < character. For example, the command

sort <somefile.txt

tells sort to read input from the file somefile.txt.You can use both input and output
redirection at the same time.The command

sort <somefile.txt >sortedfile.txt

rearranges the contents of somefile.txt and creates a new file named

sortedfile.txt.

You can also specify that the output isn’t to replace an existing file but rather should
simply be stuck onto the end (that is, appended ) with the characters >>, as in this example:

dir /b c: >listing.txt
dir /b d: >>listing.txt

The first command creates the file listing.txt, and the second appends its output
onto the end of listing.txt. (If the file listing.txt doesn’t already exist, don’t
worry: >> creates it.)

Finally, you can hook the output of one program directly to the input of another by
using the vertical bar symbol (|), usually found above the backslash () on a keyboard.
For example, the find command reads lines from the input and passes only lines containing
a designated string.The command

tasklist | find "winword"

has tasklist send its list of all programs through find which types out only the line
or lines containing «winword.» Finally,

tasklist | find "winword" >tasks.txt

connects tasklist to find, and find to a file.

Input and output redirection let you connect programs and files as if you are making
plumbing connections.The | symbol is often called a pipe for this reason, and programs
such as find are often called filters.

Note One handy filter to know about is more, a program that passes whatever it’s given as input to
its output. What makes more useful is that it pauses after printing a screen full of text. more lets
you view long listings that would otherwise scroll off the screen too quickly to read. For example, the command

tasklist | more

helps you see the entire list of programs. When you see the prompt — More — at the bottom of the
screen, press the spacebar to view the next screen full.

The standard error is another output stream available to console programs. By default, if
a program writes information to the standard error stream, the text appears in the
Command Prompt window. Programs usually use this to display important error messages
that they want you to see, even if the standard output is redirected to a file or
pipe.You can redirect standard error too, though, if you want to capture the error messages in a file.

If you’ve worked with DOS, Linux, or Unix, this is probably already familiar to you.
However, there are several input redirection variations you might not be familiar with.
Table below lists all the redirection instructions that CMD recognizes.

Input and Output Redirection

Redirection Option Action
<file Reads standard input from file.
>file Writes standard output to file.
>>file Appends standard output to file.
1>file Writes standard output to file.*
1>>file Appends standard output to file.
2>file Writes standard error to file.
2>>file Appends standard error to file.
2>&1 Directs standard error through the same stream as standard
output. Both can then be redirected to a file or piped to another program.
nextcommand Sends output to the input of nextcommand.

* The number 1 refers to the standard output stream and the number 2 to the standard error stream.

Two special forms of output redirection are output to the NUL device and output to a
printer.Windows recognizes the special filename nul in any folder on any drive and
treats it as a «black hole» file. If you issue a command and redirect its output to nul,
the output is discarded.This type of direction is useful in batch files when you want a
command to do something, but don’t want or need the user to see any error messages
it might print. For example,

net use f: /del >nul 2>nul

runs the net use command and makes sure that no output appears to the user.

Special filenames LPT1, LPT2, and so on, represent your default printer and your local
printer connected to ports LPT1, LPT2, and so on.You can direct the output of a
command to the printer using redirection to these names.You can also direct output
to network-connected printers by mapping these devices to network printers using
the net use command. Special name PRN is the same as LPT1.

In practical day-to-day use, standard output redirection lets you capture the output
of a console program into a file, where you can edit or incorporate it into your
documents. Standard error redirection is handy when you need to gather hardcopy
evidence from a program that is printing error messages. Input redirection is used most
often in a batch file setting, where you want to have a command run automatically
from input prepared ahead of time.

Here are some examples:

cmd /? | more

This has the CMD command-line shell print its built-in help information, and it
passes the text through more so it can be read a page at a time.

cmd /? > cmd.info
notepad cmd.info

This has CMD print its help information again, but this time, the text is stored in a
file, and you view the file with Notepad. (Window-based programs can be useful on occasion.)

tasklist | sort /+60 | more

This has tasklist list all running programs, and it pipes the listing through sort,
which sorts the lines starting with column 60.This produces a listing ordered by the
amount of memory used by each running program.The sorted output is piped
through more so it can be viewed a page at a time.

date /f >ping.txt
ping www.companyabc.com 2>&1 >>ping.txt

This checks whether the site www.mycompany.com can be reached through the
Internet.The results, including any errors, are stored in a file named ping.txt.You
could then view this file or analyze it with a program.

Ezoic

Понравилась статья? Поделить с друзьями:
  • Redirect error output bash
  • Redirect console error c1
  • Redefinition of function error
  • Redefinition of error xcode
  • Redefinition of class c как исправить