Очень часто приходилось слышать такое от людей, которые много времени проводят за администрированием и другими 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 Переменные
- %~I
Расширение %I, которое удаляет окружающие кавычки («»). - %~fI
Расширение %I до полного имени пути. - %~dI
Замена %I именем диска. - %~pI
Замена %I на путь. - %~nI
Замена %I одним именем файла. - %~xI
Замена %I расширением имени файла. - %~sI
Замена путем, содержащим только короткие имена. - %~aI
Замена %I атрибутами файла. - %~tI
Замена %I временем модификации файла. - %~zI
Замена %I размером файла. - %~$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 Дамы и Господа!
Осознал, что можно на эту тему еще писать и писать.
У кого-нибудь есть какие-нибудь конкретные пожелания?
Или мне самому тему придумать?
Если пожелания есть, то пишите в кАментах.
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
- 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.txtOne 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 /UIn 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.txtMulti-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 BAll 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.txtWill inadvertently interpret the “2” as part of the redirection operator.
One solution is to insert a space:
Echo %_message% >schedule.txtThis 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
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.
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.
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 commandstest.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 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:
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
andDIR > filename.txt
are identical,ECHO Hello world>filename.txt
andECHO Hello world > filename.txt
are not, even though they are both valid.
It is not ok to use spaces in>>
or2>
or2>&1
or1>&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 textHello world
(without the trailing «2») on screen (CMD.EXE would interpret it asECHO Hello world 2>file.txt
).
In Windows XP the result is no text on screen and file.txt containing the lineHello world2
, including the trailing «2» (CMD.EXE interprets it asECHO 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