Stderr to stdout windows

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:

1
2
3
4
5
6
7
C:\ dir nosuchfile.txt
 Volume in drive C has no label.
 Volume Serial Number is B8A1-5FD1
 
 Directory 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:

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

Sending the STDERR and STDOUT to Same file:

1
dir nosuchfile.txt > alloutput.log 2>&1

Here the 2>&1 instructs that the STDERR to be redirected to STDOUT which is in-turn writing out to alloutput.log file.

“Know thy commands.”
-Rushi

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

Есть 3 файловых дескриптора: stdin — стандартный ввод, stdout — стандартный вывод и stderr — стандартный поток ошибок. В скриптах 1 означает stdout, а 2 — stderr.

Практически это означает, что для программ, которые используют стандартные входные и выходные устройства, операционная система позволяет:

  • перенаправлять stdout в файл
  • перенаправлять stderr в файл
  • перенаправлять stdout в stderr
  • перенаправлять stderr в stdout
  • перенаправлять stderr и stdout в файл
  • перенаправлять stderr и stdout в stdout
  • перенаправлять stderr и stdout в stderr
  • перенаправление stderr и stdout по конвейеру

Все вышесказанное является привычной обыденностью для любого пользователя любой nix системы, но в среде Windows, данные возможности применяются крайне редко, хотя на самом деле они там есть и всё практически идентично.

А теперь примеры:

1. Перенаправление стандартного потока программы в файл с заменой содержимого файла

ping ya.ru -t > log.txt
ping ya.ru -t 1> log.txt

при этом на экран ничего кроме ошибок не выводится, а все записывается в лог. Если остановить пинг, и запустить заново, предыдущий лог полностью затирается новым.

2. Перенаправление стандартного потока программы в файл с до записью содержимого лога

ping ya.ru -t >> log.txt

Тоже самое, но при прерывание пинга и начале нового, старое содержимое лога не затрется, а новое дописывается в конец

ping ya.ru -t 1>> log.txt

3. Перенаправление потока ошибок программы в фаил с заменой содержимого

ping ya.ru -t 2> log.txt

при этом, стандартный поток программы пойдет на экран, а ошибки будут записаны в лог, с заменой содержимого.

4. То же самое, но с до записью содержимого лога.

ping ya.ru -t 2>> log.txt

5. Следующая конструкция позволяет перенаправить информацию между потоками (между стандартным потоком и потоком ошибок, или наоборот).

ping ya.ru > log.txt 2>&1

или с до записью лога

ping ya.ru >> log.txt 2>&1

В данном примере стандартный поток ошибок пересылается в стандартный поток (конструкция 2>&1) а потом стандартный поток (уже с завернутым в него потоком ошибок) посылается в лог.

6. В этом примере все наоборот, стандартный поток, пересылается в поток ошибок и уже поток ошибок перенаправляется в лог:

ping ya.ru > log.txt 1>&2

или с до записью лога

ping ya.ru >> log.txt 1>&2

7. По аналогии с Linux системами в Windows можно перенаправить весь или часть вывода программы в виртуальное устройство, а проще говоря слить в мусор.

Таким устройством является nul, и делать перенаправление в него можно используя все выше представленные комбинации. Например

ping ya.ru > nul

В Linux есть еще одна конструкция перенаправления, а именно &>/var/log/log.txt, она перенаправляет ВСЕ без исключения потоки программы в указанное место, по сути являясь более коротким и более грамотным аналогом конструкции >log.txt 1>&2. Но к сожалению в Windows это не работает.

А теперь давайте немного разберемся в прикладных различиях между работой данных методов. В нормальных приложениях все разбито на потоки, но у большинства виндовых утилит это не так, пинг например, пишет все в стандартный поток (на экран), поэтому для него конструкция вида 2> не имеет смысла. Но есть еще не виндовые утилиты, для примера возьмем curl (мой любимый).

Он разделяет 3 вида вывода, вывод полезной информации, вывод служебной информации и вывод ошибок. Если перенаправить вывод так: > или >> или 1> или 1>> то по завершению запроса отобразится служебная информация о запросе, а вся полезная информация уйдет в лог (это именно то, что уходит по конвейеру |).

А теперь сделаем заведомо ошибочный запрос, изменив протокол http на http3 не меняя вывода в лог. В итоге мы получим ошибку на экране.

Изменим вывод в лог на один из этих: 2> или 2>> ошибка ранее выводившаяся на экран, попала в лог, и на экране ничего не будет (служебной информации нет, так как запрос произведен не был).

Вернемся к первому скриншоту на котором мы видим вывод служебной информации, по сути, не будь у курла ключа -s который подавляет вывод служебной информации, нам пришлось бы пользоваться конструкциями из пятого и шестого примеров.

И вывод был бы таким:

То есть, полная тишина, вся информация, как то полезный вывод, ошибки программы, служебная информация, все ушло в лог.

На данном скриншоте, конструкцией 2>&1 мы завернули поток ошибок в стандартный поток, а конструкцией > 5555.txt стандартный поток перенаправили в лог. Если вместо > 5555.txt использовать 2> 5555.txt, то есть перенаправить в лог стандартный поток ошибок, мы увидим весь вывод программы (и ошибки, и служебную информацию и полезный вывод) на экране. Конструкция 2>&1 имеет больший приоритет, а по ней уже все завернуто в стандартный поток.

Делать пример с заворотом стандартного потока в поток ошибок (1>&2) я не буду, ибо там все точно так же.

Надеюсь логика понятна…

Так же с помощью символа < можно прочитать входные данные для заданной команды не с клавиатуры, а из определенного (заранее подготовленного) файла. Для примера возьмем реальный и вполне полезный случай. Например, у нас есть файл log.txt и нам надо посчитать сколько в нем строк. Сделать это можно с помощью такой конструкции

find /c /v "" log.txt

но вывод будет не совсем приемлемым.

А вот если сделать так:

find /c /v "" < log.txt

то все будет именно так как надо.

Это происходит потому что в первом случае, файл обрабатывается как файл, а во втором, как поток (аналог линуксового конвейера cat log.txt |) в общем, < это виндовый аналог cat со всеми вытекающими.

Источник

Каталог оборудования

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Производители

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Функциональные группы

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Introduction

A console program (i.e. a program that is executed from the command line) can write its output on two separate streams: stdout and stderr. Theoretically stdout is used to display the program results and stderr is used to write error messages.

In a normal execution text written on both the stdout and the stderr isdisplayed on the console.

Lets try with an example. The following simplistic C# code writes a message on stdout and another message in stderr.


using System;
namespace TestStdout
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Error.WriteLine(«STDERR message»);
            Console.Out.WriteLine(«STDOUT message»);
        }
    }
}

If we execute this program on the windows command line we get


D:\test>TestStdout.exe
STDERR message
STDOUT message

D:\test>

Redirection

The redirection of stdout and stderr is well known by Linux users but strangely not so much popular for Windows users. However, it works (nearly) the same way with both operating systems

Redirect stdout to a file

To redirect the program output (stdout) to a file, use the operator >


D:\test>TestStdout.exe >out.txt
STDERR message

D:\test>type out.txt
STDOUT message

D:\test>

To get rid of stdout you may redirect it to a special file called NUL that throws away anything sent to it. (note that in Linux it is called /dev/null).


D:\test>TestStdout.exe >NUL
STDERR message

D:\test>

Redirect stderr to a file

To redirect the stderr you use the operator 2>


D:\test>TestStdout.exe 2>err.txt
STDOUT message

D:\test>type err.txt
STDERR message

D:\test>

You may also redirect stderr to NUL if you want to get rid of it


D:\test>TestStdout.exe  2>NUL
STDOUT message


D:\test>

Redirect both stdout and stderr to a file

You may combine > and 2> to redirect both stdout and stderr


D:\test>TestStdout.exe >out.txt 2>err.txt

D:\test>

It is also possible to redirect both stdout and stderr to the same file by using 2>&1 to first redirect stderr to stdout (&1 is in fact stdout) and redirect stdout to a file.


D:\test>TestStdout.exe >OutAndErr.txt 2>&1

D:\test>type OutAndErr.txt
STDERR message
STDOUT message

D:\test>

Redirecting to the clipboard

On Windows sytsems, it is possible to redirect directly to the clipboard instead of redirecting to a file (thank yo to Scott Hanselman for this trick ) by using | clip

You can redirect stdout to the clipboard


D:\test>TestStdout.exe |clip
STDERR message


D:\test>

You can redirect both stdout and stderr to the clipboard by first redirecting stderr to stdout


D:\test>TestStdout.exe 2>&1 |clip


D:\test>

You can redirect only stderr to the clipboard

But this is tricky: you have to redirect stderr to stdout and stdout  to null and pipe to clip. Warning swapping the operations does not get the correct result.


D:\test>TestStdout.exe 2>&1 >NUL |clip


D:\test>

Skip to content

Redirect StdErr to StdOut on Windows

Subj.

Finally, the correct command should be like this:

myUtilApp -prm1 -prm2 file1 2>&1 >> myUtilApp.log

So, it should have “2>&1” and then “>>” separately.

Note: using the old stderr.exe utility is a very bad option because it lead to problems in 30% cases. It simply reports – “program is not fit into memory” and fail to execute the command at all.


  • SS64
  • CMD
  • How-to

How-to: Redirection

command > filename
command
>&n
 
Redirect command output to a file
Redirect command output to the input of handle n
 
command >> filename
 
APPEND into a file
 
command < filename
command
<&n
 
Type a text file and pass the text to command.
Read input from handle n and write it to command.
 
commandA | commandB
 
Pipe the output from commandA into commandB
 
commandA & commandB Run commandA and then run commandB
commandA && commandB Run commandA, if it succeeds then run commandB
commandA || commandB Run commandA, if it fails then run commandB

commandA && commandB || commandC

If commandA succeeds run commandB, if commandA fails run commandC
If commandB fails, that will also trigger running commandC.

Success and failure are based on the Exit Code of the command.
In most cases the Exit Code is the same as the ErrorLevel

For clarity the syntax on this page has spaces before and after the redirection operators, in practice you may want to omit those to avoid additional space characters being added to the output. Echo Demo Text> Demofile.txt

Numeric handles:

STDIN  = 0  Keyboard input
STDOUT = 1  Text output
STDERR = 2  Error text output
UNDEFINED = 3-9 (In PowerShell 3.0+ these are defined)

When redirection is performed without specifying a numeric handle, the the default < redirection input operator is zero (0) and the default > redirection output operator is one (1). This means that ‘>‘ alone will not redirect error messages.

   command 2> filename       Redirect any error message into a file
   command 2>> filename      Append any error message into a file
  (command)2> filename       Redirect any CMD.exe error into a file
   command > file 2>&1       Redirect errors and output to one file
   command > fileA 2> fileB  Redirect output and errors to separate files

   command 2>&1 >filename    This will fail!

Redirect to NUL (hide errors)

   command 2> nul            Redirect error messages to NUL
   command >nul 2>&1         Redirect error and output to NUL
   command >filename 2> nul  Redirect output to file but suppress error
  (command)>filename 2> nul  Redirect output to file but suppress CMD.exe errors

Any long filenames must be surrounded in «double quotes».
A CMD error is an error raised by the command processor itself rather than the program/command.

Some commands, (e.g. COPY) do not place all their error mesages on the error stream, so to capture those you must redirect both STDOUT and
STDERR with command > file 2>&1

Redirection with > or 2> will overwrite any existing file.

You can also redirect to a printer with > PRN or >LPT1 or to the console with >CON

To prevent the > and < characters from causing redirection, escape with a caret: ^> or ^<

Redirection — issues with trailing numbers

Redirecting a string (or variable containing a string) will fail to work properly if there is a single numeral at the end, anything from 0 to 9.
e.g. this will fail:
Set _demo=abc 5
Echo %_demo%>>demofile.txt

One workaround for this is to add a space before the ‘>>’ but that space will end up in the output.
Moving the redirection operator to the front of the line completely avoids this issue, but is undocumented syntax.:

Set _demo=abc 5
>>demofile.txt Echo %_demo%

Create a new file

Create an empty file using the NUL device:

Type NUL >EmptyFile.txt
or
Copy NUL EmptyFile.txt
or
BREAK > EmptyFile.txt

Multiple commands on one line

In a batch file the default behaviour is to read and expand variables one line at a time, if you use & to run multiple commands on a single line, then any variable changes will not be visible until execution moves to the next line. For example:

 SET /P _cost=»Enter the price: » & ECHO %_cost%

This behaviour can be changed using SETLOCAL EnableDelayedExpansion

Redirect multiple lines

Redirect multiple lines by bracketing a set of commands:

(
  Echo sample text1
  Echo sample text2
) > c:\logfile.txt

Unicode

The CMD Shell can redirect ASCII/ANSI (the default) or Unicode (UCS-2 le) but not UTF-8.
This can be selected by launching CMD /A or CMD /U

In Windows 7 and earlier versions of Windows, the redirection operator ‘>’ would strip many Extended ASCII /Unicode characters from the output.
Windows 10 no longer does this.

Pipes and CMD.exe

You can redirect and execute a batch file into CMD.exe with:

CMD < sample.cmd

Surprisingly this will work with any file extension (.txt .xls etc) if the file contains text then CMD will attempt to execute it. No sanity checking is performed.

When a command is piped into any external command/utility ( command | command ) this will instantiate a new CMD.exe instance.
e.g.
TYPE test.txt | FIND «Smith»

Is in effect running:

TYPE test.txt | cmd.exe /S /D /C FIND «Smith»

This has a couple of side effects:
If the items being piped (the left hand side of the pipe) include any caret escape characters ^ they will need to be doubled up so that they survive into the new CMD shell.
Any newline (CR/LF) characters in the first command will be turned into & operators. (see StackOverflow)

On modern hardware, starting a new CMD shell has no noticable effect on performance.

For example, this syntax works, but would fail if the second or subsequent (piped) lines were indented with a space:
@Echo Off
Echo abc def |^
Find «abc» |^
Find «def»> outfile.txt

Multi-line single commands with lots of parameters, can be indented as in this example:

Echo abc def ^
  ghi jkl ^

  mno pqr

Redirection anywhere on the line

Although the redirection operator traditionally appears at the end of a command line, there is no requirement that it do so.
All of these commands are equivalent:

Echo A B>C
Echo A>C B
Echo>C A B
>C Echo A B

All of them Echo «A B» to the file «C».

If the command involves a pipe such as DIR /b | SORT /r then you will still want to put the redirection at the end so that it captures the result of the SORT, but there are some advantages to putting the redirection at the start of the line.

Code like this:

Set _message=Meet at 2
Echo %_message%>schedule.txt

Will inadvertently interpret the “2” as part of the redirection operator.

One solution is to insert a space:

Echo %_message% >schedule.txt 

This assumes that the space won’t cause a problem. If you’re in a case where that space will indeed cause a problem, you can use the trick above to move the redirection operator to a location where it won’t cause any trouble:

>schedule.txt Echo %_message%  

Example via Raymond Chen

The idea of redirection anywhere in the line was first introduced in version 2 of sh, written by Ken Thompson in 1972.

Exit Codes

If the filename or command is not found then redirection will set an Exit Code of 1

When redirecting the output of DIR to a file, you may notice that the output file (if in the same folder) will be listed with a size of 0 bytes. The command interpreter first creates the empty destination file, then runs the DIR command and finally saves the redirected text into the file.

The maximum number of consecutive pipes is 2042

Examples

   DIR >MyFileListing.txt
   
   DIR /o:n >"Another list of Files.txt"

   DIR C:\ >List_of_C.txt 2>errorlog.txt

   DIR C:\ >List_of_C.txt & DIR D:\ >List_of_D.txt

   ECHO y| DEL *.txt

   ECHO Some text ^<html tag^> more text

   COPY nul empty.txt

   MEM /C >>MemLog.txt

   Date /T >>MemLog.txt

   SORT < MyTextFile.txt

   SET _output=%_missing% 2>nul
   
   FIND /i "Jones" < names.txt >logfile.txt

   (TYPE logfile.txt >> newfile.txt) 2>nul

“Stupidity, outrage, vanity, cruelty, iniquity, bad faith, falsehood,
we fail to see the whole array when it is facing in the same direction as we” ~ Jean Rostand (French Historian)

Related commands

CON — Console device.
conIN$
and conOUT$ behave like stdin and stdout, or 0 and 1 streams but only with internal commands.
SORT — Sort input.
CMD Syntax
TYPE — Display the contents of one or more text files.
Command Redirection — Microsoft Help page (archived)
Successive redirections explained (1>&3 ) — Stack Overflow.
Equivalent PowerShell: Redirection — Spooling output to a file, piping input.
Equivalent bash command (Linux): Redirection — Spooling output to a file, piping input.


Copyright © 1999-2025 SS64.com
Some rights reserved

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Bootcamp последняя версия windows
  • Geforce mx230 драйвер windows 10
  • Aten usb to serial bridge windows 10
  • Подключение принтера через другой компьютер в windows 7
  • Очиститель оперативной памяти windows 10