I/O Redirection#

The Bourne Again Shell supports multiple operators to manipulate file descriptors. They can be opened, closed, redirected to other files or duplicated. Most often redirection and duplication of the standard file descriptors is used. This I/O manipulation is the core functionality to combine simple individual tools.

Redirection Operators#

The following table lists the most common redirection operators in their general form:

Operator

Result

<n file

Open file for reading on fd n

n> file

Open file for writing (truncate) on fd n. Redirect fd n if it already exist

n>> file

Open file for writing (append) on fd n. Redirect fd n if it already exist

n>&m

Make fd n a copy of fd m (which should be open for writing)

n<&m

Make fd n a copy of fd m (which should be open for reading)

Often they have abbreviated forms when dealing with the standard file descriptors:

Operator

Result

> file

Redirect stdout to a file (truncate)

2> file

Redirect stderr to a file (truncate)

>> file

Redirect stdout to a file (append)

2>> file

Redirect stderr to a file (append)

< file

Redirect stdin to a file

2>&1

Make stderr a copy of stdout

1>&2

Make stdout a copy of stderr

\(cmd_1\) | \(cmd_2\)

Redirect \(cmd_1\)’s stdout to \(cmd_2\)’s stdin

\(cmd_1\) |& \(cmd_2\)

Short for \(cmd_1\) 2>&1 | \(cmd_2\)