Table of Contents

What are Redirection Operators in Dos with example and how-to?

About

This page talks about shell redirection operator|operator in DOS.

The order of redirections is significant when redirecting a standard error stream to a standard output stream. See order of redirections

Handle

The standard predefined stream that can handle the operators are the below one and have a unique id

Handle Numeric equivalent of handle (Unique id) Description
nul or another string nul Suppress the character flow
STDIN 0 Keyboard input
STDOUT 1 Output to the Command Prompt window
STDERR 2 Error output to the Command Prompt window
UNDEFINED 3-9 These handles are defined individually by the application and are specific to each tool.

Operators

Redirecting Output

> (Greater than)

Greater than > redirect:

to:

Syntax:

[SourceHandleId]>[&]TargetWord

where:

Example:

command 2> stderr.log
command 1> stdout.log
Rem or simply
command > stdout.log
set FILE_STDERR=err.log
command 2> %FILE_STDERR%
command 2>nul
dir >c:\file.txt 2>&1

» (Append)

>> has the same syntax than > but it will append to the file. It will not create it or truncate as > does.

Redirecting Input - < (Less than)

<&: Reads the input from one handle and writes it to the output of another handle.

[StandardStreamHandleId]<[&]SourceWord

where:

Example:

sort  <file.txt
REM or 
<file.txt  sort  
2<&1

Redirecting Output to Input - | (Pipeline or Command Chaining)

The | pipeline (See also DOS - Filter Commands) operator redirect the stdout (not the stderr) of the source program to the stdin of the target program

Syntax:

command parameter | command parameter

If you want to pipe :

mySourceCommand  2>&1 | myTargetCommand
mySourceCommand  2>&1 1>null | myTargetCommand

Order of precedence

The order of the standard streams redirection is important

The order of redirections is significant when you redirect the standard streams. The redirections of standard streams happens from left to right (and not from right to left)

dir >targetFile.txt 2>&1

redirects to the file:

  • both standard output (file descriptor 1)
  • and standard error (file descriptor 2)
dir 2>&1 >targetFile.txt

redirects only the standard output to the file.

the standard error was made a copy of the standard output before the standard output was redirected to the file.

The redirections may appears before or after the command

command 2>&1 >targetFile.txt
Rem is equivalent to
2>&1 >targetFile.txt command
sort < file_to_be_sorted.txt > sorted_file_list.txt
Rem is equivalent to
< fileToBeSorted.txt > fileSorted.txt sort

How to

Create a file with content

DOS - File

set myFile=myFile.sql
> %myFile% echo.WHENEVER SQLERROR EXIT SQL.SQLCODE
>> %myFile% echo.select * from dual;
>> %myFile% echo.exit;
>> %myFile% echo.

Content:

WHENEVER SQLERROR EXIT SQL.SQLCODE
select * from dual;
exit;

Documentation / Reference