Recent Changes - Search:

Basics

Languages

Tools

OS

Resources

PmWiki

pmwiki.org

edit SideBar

Redirection

Redirection is the process by which information that was supposed to go to one location is sent to another.

Output redirection

Most common of all is the output redirection, which allows to save too long (or cumbersome) output into a file instead of displaying it on the terminal window.

someCommand > outputFile

where someCommand is a command that generally produces output to the terminal and outputFile is the name of a file in which output will be stored.

Error redirection

In Bash, output comes in two "flavours": standard and error. The above only redirects standard output and error messages will still be displayed on the terminal.

To redirect errors into their own file errorFile:

someCommand 2> errorFile

Redirecting both

Using the above, only one of the two outputs is redirected, meaning that potentially important context might be missing. To redirect both outputs:

someCommand > outputFile 2>&1

which redirects standard output into outputFile, and error output (output channel #2) into standard output (output channel #1), which itself has already been defined as going into outputFile. The end result is that everything goes into outputFile.

Redirecting from within

When writing a script, it is often useful to pre-set output redirection. This is done in the header of the script. For example, to separate Bash error messages from the main output:

#!/bin/bash  --
exec 2> errorFile
Edit - History - Print - Recent Changes - Search
Page last modified on July 07, 2016, at 05:14 PM