input / output redirection

Three standard file descriptors :
1. stdin 0 - Standard input to the program.
2. stdout 1 - Standard output from the program.
3. stderr 2 - Standard error output from the program.
PURPOSECOMMAND
redirect std output to filename> filename or 1> filename
append std out to filename>> filename
append std out and std err to filename>> filename 2>&1 or 1>> filename 2>&1
take input from filename< filename or 0 < filename
redirect std error to filename2> filename
redirect std out and std error to filename1> filename 2>&1 or > filename 2>&1
Some examples of using I/O redirection
# cat goodfile badfile 1> output 2> errors
This command redirects the normal output (contents of goodfile) to the file output and sends any errors (about badfile not existing, for example) to the file errors.
# mail user_id < textfile 2> errors
This command redirects the input for the mail command to come from file textfile and any errors are redirected to the file errors.
# find / -name xyz -print 1> abc 2>&1
This command redirects the normal output to the file abc. The construct “2>&1” says “send error output to the same place we directed normal output”.
Note that the order is important; command 2>&1 1>file does not do the same as command 1>file 2>&1. This is because the 2>&1 construction means redirect standard error to the place where standard output currently goes. The construction command 2>&1 1>file will first redirect standard error to where standard output goes (probably the terminal, which is where standard error goes by default anyway) then will redirect standard output to file. This is probably not what was intended.
# ( grep Bob filex > out ) 2> err
– any output of the grep command is sent to the file out and any errors are sent to the file err.
# find . -name xyz -print 2>/dev/null


This runs the find command, but sends any error output (due to inaccessible directories, for example), to /dev/null. Use with care, unless error output really is of no interest.

0 comments:

Post a Comment