Windows перенаправление вывода в файл

What to Know

  • The > redirection operator goes between the command and the file name, like ipconfig > output.txt.
  • If the file already exists, it’ll be overwritten. If it doesn’t, it will be created.
  • The >> operator appends the file. Instead of overwriting the file, it appends the command output to the end of it.

Use a redirection operator to redirect the output of a command to a file. All the information displayed in Command Prompt after running a command can be saved to a file, which you can reference later or manipulate however you like.

How to Use Redirection Operators

While there are several redirection operators, two, in particular, are used to output the results of a command to a file: the greater-than sign (>) and the double greater-than sign (>>).

The easiest way to learn how to use these redirection operators is to see some examples:

Export Network Settings to a File

 ipconfig /all > networksettings.txt

In this example, all the information normally seen on screen after running ipconfig /all, is saved to a file by the name of networksettings.txt. It’s stored in the folder to the left of the command, the root of the D: drive in this case.

The > redirection operator goes between the command and the filename. If the file already exists, it’ll be overwritten. If it doesn’t already exist, it will be created.

Although a file will be created if it doesn’t already exist, folders will not. To save the command output to a file in a specific folder that doesn’t yet exist, first, create the folder and then run the command. Make folders without leaving Command Prompt with the mkdir command.

Export Ping Results to a File

 ping 192.168.86.1 > "C:\Users\jonfi\Desktop\Ping Results.txt"

Here, when the ping command is executed, Command Prompt outputs the results to a file by the name of Ping Results.txt located on the jonfi user’s desktop, at C:\Users\jonfi\Desktop. The entire file path in wrapped in quotes because a space involved.

Remember, when using the > redirection operator, the file specified is created if it doesn’t already exist and is overwritten if it does exist.

The Append Redirection Operator

The double-arrow operator appends, rather than replaces, a file:

 ipconfig /all >> \\server\files\officenetsettings.log

This example uses the >> redirection operator which functions in much the same way as the > operator, only instead of overwriting the output file if it exists, it appends the command output to the end of the file.

Here’s an example of what this LOG file might look like after a command has been exported to it:

The >> redirection operator is useful when you’re collecting similar information from different computers or commands, and you’d like all that data in a single file.

The above redirection operator examples are within the context of Command Prompt, but you can also use them in a BAT file. When you use a BAT file to pipe a command’s output to a text file, the exact same commands described above are used, but instead of pressing Enter to run them, you just have to open the BAT file.

Use Redirection Operators in Batch Files

Redirection operators work in batch files by including the command just as you would from the Command Prompt:

 tracert yahoo.com > C:\yahootracert.txt

The above is an example of how to make a batch file that uses a redirection operator with the tracert command.

The yahootracert.txt file (shown above) will be created on the C: drive several seconds after executing the sample.bat file. Like the other examples above, the file shows everything Command Prompt would have revealed if the redirection operator wasn’t used.

Export Text Results in Terminal

Terminal provides an easy way to create a text file containing the contents of whatever you see in Command Prompt. Although the same redirection operator described above works in Terminal, too, this method is useful for when you didn’t use it.

To save the results from a Terminal window, right-click the tab you’re working in and select Export Text. You can then choose where to save the TXT file.

Thanks for letting us know!

Get the Latest Tech News Delivered Every Day

Subscribe

Очень часто приходилось слышать такое от людей, которые много времени проводят за администрированием и другими IT-забавами.

Я, за не очень долгий опыт реального администрирования пришел к обратному выводу. В консоли (командной строке) В Windows можно выполнять очень много разных операций, которые стандартными возможностями не выполняются или выполняются некорректно/неудобно/долго (нужное подчеркнуть)

Совсем недавно где-то на Хабре промелькнуло высказывание из серии «Не думал, что консоль в Виндах что-то может. Хотелось бы узнать об этом побольше».

Вот так и возникло желание написать небольшую статью про основные возможности консоли.

Про самые стандартные команды консоли можно узнать тривиальным способом:
заходим в cmd и пишем:

help

В сообщении я не буду подробно рассматривать команды типа copy (т.е. совсем тривиальные) так как о них можно прочитать введя команду типа

copy /?

1. Ввод-вывод

Рассмотреть же я попытаюсь команды, которые в основном хэлпе не написаны или описаны недостаточно подробно.
Для начала хотелось бы написать про операторы перенаправления ввода-вывода.
Таковыми операторами являются >, >>, <.
Они нам могут пригодиться как минимум в трех ситуациях:

  • Просмотр логов бат-файла
  • Чтение длинных хелпов по консольным утилитам
  • Подхватывание каких-либо переменных из лежащего рядом файла

При желании примеров можно придумать сколько угодно.

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

команда > имя_файла

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

команда >> имя_файла

С помощью символа < можно прочитать входные данные для заданной команды не с клавиатуры, а из определенного (заранее подготовленного) файла:

команда < имя_файла

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

1. Вывод встроенной справки для команды COPY в файл copy.txt:

COPY /? > copy.txt

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

XCOPY /? >> copy.txt

3. Ввод новой даты из файла date.txt (DATE — это команда для просмотра и изменения системной даты):

DATE < date.txt

2. FOR… DO

Второй командой, которую бы хотелось рассмотреть является FOR ... DO
Эта команда, так же как и многие другие достаточно подробно описана на сайте WindowsFAQ.
Я же хочу остановиться на двух наиболее важных пунктах

2.1 Переменные
  1. %~I
    Расширение %I, которое удаляет окружающие кавычки («»).
  2. %~fI
    Расширение %I до полного имени пути.
  3. %~dI
    Замена %I именем диска.
  4. %~pI
    Замена %I на путь.
  5. %~nI
    Замена %I одним именем файла.
  6. %~xI
    Замена %I расширением имени файла.
  7. %~sI
    Замена путем, содержащим только короткие имена.
  8. %~aI
    Замена %I атрибутами файла.
  9. %~tI
    Замена %I временем модификации файла.
  10. %~zI
    Замена %I размером файла.
  11. %~$PATH:I
    Поиск в каталогах, перечисленных в переменной среды PATH, и замена %I полным именем первого найденного файла. Если переменная среды не определена или поиск не обнаружил файлов, модификатор выдает пустую строку.

Очевидно, что с помощью такого широкого набора переменных мы можем практически полностью отвязаться от индивидуальных особенностей конкретного экземпляра операционной системы и => избежать проблем например из-за того, что система встала на диск E:, а не на C:.

2.2 Работа с файлами

Чтобы произвести разбор файла, игнорируя комментарии, можно использовать следующую команду:

for /F "eol=; tokens=2,3* delims=," %i in (myfile.txt) do @echo %i %j %k

Данная команда производит разбор каждой строки в файле Myfile.txt, игнорируя строки, начинающиеся с точки с запятой, и передает второй и третий элементы из каждой строки в тело цикла команды FOR. Элементы разделяются запятыми и/или пробелами. Тело инструкции FOR использует %i для получения второго элемента, %j для получения третьего элемента и %k для получения оставшихся элементов в строке. Если имена файлов содержат пробелы, их следует заключать в кавычки (например, «ИмяФайла»). Для использования кавычек необходима команда usebackq. В противном случае кавычки рассматриваются как определение символьной строки для разбора.

Переменная %i объявлена явно в инструкции FOR, а %j и %k объявлены неявно с помощью tokens=. С помощью tokens= можно указать до 26 элементов, если это не вызовет попытки объявить переменную с именем, большим буквы «z» или «Z».

Для разбора вывода команды с помощью помещения параметра МножествоИменФайлов в скобки можно использовать следующую команду:
for /F "usebackq delims==" %i IN (`set`) DO @echo %i

В данном примере перечисляются имена переменных среды в текущем окружении.

Пофантазируем?..

Итак, что нам дают всего эти две команды?

Ну вот возьмем для примера утилиту, которая лежит на сайте Microsoft и называется psexec. Она позволяет нам, зная логин и пароль машины, подключиться к ней и выполнить произвольные действия

в консольном режиме

Допустим, что у нас есть домен Windows и пароль доменного администратора.
Нам нужно подключиться ко всем машинам и удалить все файлы с маской *.mp3 с диска C:.

Для начала — как получить список всех компьютеров сети.
Я это делаю так:

FOR /F "skip=3 delims=\ " %%A IN ('NET VIEW') DO ECHO %%A>>c:\comps.txt

Имеем список всех компов в сети в столбик — как раз в том формате, который принимает psexec.
Правда, будут проблемы с русскими названиями компов, но это ведь не актуальная проблема, да?

Теперь про PsExec. Скачать его можно тут.
Синтаксис описан там же.

Нас интересует вот какая команда
c:\psexec.exe @c:\comps.txt -u username -p password -c MP3DELETE.bat

Содержимое .bat — файла:
cd /d c:\
for /r %%p in (*.mp3) do del %%p

Само собой, задача чисто абстрактная. Мне просто хотелось показать, что консоль в Windows на самом деле весьма могуча и позволяет красиво и удобно решать многие задачи.

А уж как здорово одним нажатием на bat-ник устанавливать пользователям софт в unattended-режиме…

Спасибо за внимание! Жду критики и предложений…

UPD.1 Спасибо большое maxshopen за инвайт и первую карму!
Благодаря ему и всем плюсующим с радостью перенес свою первую статью в свой первый блог — Windows.

UPD.2 Спасибо, Hint

copy con file.txt
Перенаправляет вывод с клавиатуры в файл (CTRL+Z — завершение ввода).
type file.txt >prn
Печает на принтере file.txt

UPD.3 Дамы и Господа!
Осознал, что можно на эту тему еще писать и писать.
У кого-нибудь есть какие-нибудь конкретные пожелания?
Или мне самому тему придумать?
Если пожелания есть, то пишите в кАментах.

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

Есть 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.

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:

dir test.exe > myoutput.txt

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:

dir test.exe >> myoutput.txt

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: 

dir test.exe > myoutput.txt 2> output.err

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.

dir test.exe 1> myoutput.txt 2>&1

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:

dir test.exe 1> myoutput.txt 2>nul

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.

Related Posts

  • How to Fix a “This file does not have an app associated with it” Error on Windows
  • How to Fix an Update Error 0x800705b4 on Windows
  • How to Resolve “A JavaScript error occured in the main process” Error on Windows
  • How to Fix the Network Discovery Is Turned Off Error on Windows
  • How to Change Folder Icons in Windows

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; loaded in 0.0014 seconds

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Создание виртуальной машины в windows 10 virtualbox
  • Настройка пользователей windows server 2003
  • Мини образ windows xp для флешки
  • Проводник не обновляет содержимое папки windows 10
  • Download avast for windows 10