Name | Default destination | Use in redirection | File Descriptor Number |
---|---|---|---|
STDIN | Computer keyboard | < or 0< |
0 |
STDOUT | Computer monitor | > or 1> |
1 |
STDERR | Computer monitor | 2> |
2 |
There are a few common BASH redirectors, these are as follows:
Redirector | Explanation |
---|---|
> or 1> |
Redirects STDOUT. If redirection is to a file, the current contents of the file are overwritten |
>> or 1>> |
Redirects STDOUT. If redirection is a file, the output is appended to the file |
2> |
Redirects STDERR |
2> /dev/null |
Redirects STDERR to null (discards messages) |
> [file] 2>&1 |
Redirect STOUT and STDERR to overwrite the same [file] |
&> [file] |
Same as above |
>> [file] 2>&1 |
Redirect STOUD and STERR to append the same [file] |
&> [file] |
Same as above |
< or 0< |
Redirects STDIN |
Order is important. The example below redirects STOUT to
file
and then redirects STDERR to the same filefile 2>&1
However, in the following example, STERR is sent to the standard destination (i.e. the terminal) and STDOUT is directed to
file
.2>&1 > file
Another form of redirection used in BASH is the pipe ('|'). When used with commands, this will take the output of the first command and feed it in to the 2nd command. It is possible to chain together multiple commands with many pipes.
For example:
[user@host ~]$ ls -R /var/lib | grep -i 'x' | less
Will list out (recursively) the contents of /var/lib
, then pass that stream to grep
to search for 'x' and the output of that command will be passed to the less
command to show the results in the terminal one page at a time.
It should also be noted that if a STDERR or STDOUT redirection is used before a pipe, then all of the STDERR and STDOUT stream will be redirected and there will be nothing to pipe to the next command.
In order to overcome this, thetee
command can be used
If you cannot enter the pipe character (|) then you can hold Alt and type 1, 2, 4 on the keypad
The tee
command copies STDIN to its STDOUT as well as the output to the files named in command arguements.
For example:
[user@host ~]$ ls -R /var/lib | tee /tmp/lib-contents | grep -i 'x' | less
Will list out /var/lib
recursively, dump the output in to /tmp/lib-contents
and still allow that stream to flow to grep
and less
as before.
If used at the end of a pipeline, then the final product of the pipeline can be shown in the terminal as well as a file.