Skip to content

Redirection

rbaltrusch edited this page Feb 15, 2021 · 4 revisions

Redirection

It is possible in batch to redirect output of commands to files or other commands, as well as redirect content of a file to a command or chain commands depending on if an error occured.

Output redirection

To redirect the output of a command to a file, one may use the syntax in the following example, which writes hello to the file test.txt:

echo hello>test.txt

Note the lack of whitespace (a detailed explanation can be found here).

This may also be used with commands other than echo. The following example writes a list of the names of files and folders contained in the current directory to a file called contents.txt:

echo dir /b>contents.txt

Note that the redirection operator ( > ) writes to a new file under the specified name. If the file exists, its contents are overwritten. If appending to the existing file contents is desired instead, one may use the appending redirection operator ( >> ), as below:

echo line1>test.txt
echo line2>>test.txt

File content redirection

The file content redirection operator ( < ) may be used to redirect file content to a command that expects user input. The example below highlights the most useful use of this operator, where we use it to store text in a variable. Note the set /p, which usually expects an input from the user:

set /p filetext= <my_file.txt

Piping

Other command redirection operators (also called pipes) include:

  • command1 | command2 (pass the output of command1 to command2)
  • command1 & command2 (run command1, then command2) (An example can be found here.)
  • command1 && command2 (run command1, then command2 if no errors occured)
  • command1 || command2 (run command1, then command2 if errors occured)

More details may be found here

Clone this wiki locally