Thursday, 18 April 2013

I/O Redirection in Bash

Since Bash is a superset of Bourne shell, the IO redirection is the same across the Bourne shell family. To find out exactly which shell you are using in Unix or Linux, typing in command
echo $SHELL
shall display an executable command with its path, for example
PathShell
/bin/shBourne shell
/bin/bashBourne Again SHell
/bin/cshC SHell
/bin/kshKorn SHell

Bash takes input from standard input (stdin), writes output to standard output (stdout), and writes error output to standard error (stderr). Standard input is connected to the terminal keyboard, while standard output and error are connected to the terminal screen, by default. Redirection of I/O is accomplished by using a redirection metacharacter followed by the desired destination (stdout & stderr) or source (stdin). Bash uses file descriptor numbers to refer to the standard I/O, where 0 is standard input, 1 is standard output, and 2 is standard error. Below are the common redirection for the Bourne shell family:

Meta CharacterAction
>Redirect standard output
>>Append to standard output
2>Redirect standard error
2>&1Redirect standard error to standard ouput
2>&1|Redirect standard error to standard ouput, and pipe them to another command
<Redirect standard input
|Pipe standard output to another command

Please note that because < and > are referring to standard input and output respectively, the numbers 0 and 1 are not required in this case.

No comments:

Post a Comment