Linux Shell redirection such as 2>&1

Posted on January 21, 2009. Filed under: Linux |

Linux Shell redirection such as 2>&1

Following are two methods to redirect STDERR and STDOUT to logfile
a) 2>&1 
Some examples :
           ls 2>1      There is no error about  “file 2 is not exist”, but there will be a null file 1
           ls xxx 2>1   The error “ls: XXX: No such file or directory” will output to file 1
           ls xxx 2>&1  There is no file 1, but the stderr will redirect to stdout
           ls xxx >out.txt 2>&1, (or ‘ls xxx 1>out.txt 2>&1’)    redirect ‘>’ default is 1, then the stderr and stdout are all outputted to file out.txt

Other examples from another reference:
# Look for ERROR string in both stdout and stderr.
foo 2>&1 | grep ERROR

# Run the less pager without stderr screwing up the output.
foo 2>&1 | less

# Send stdout/err to file (with append) and terminal.
foo 2>&1 |tee /dev/tty >>outfile

# Send stderr to normal location and stdout to file.
foo >outfile1 2>&1 >outfile2
Note that that last one will not direct stderr to outfile2 – it redirects it to what stdout was when the argument was encountered (outfile1) and then redirects stdout to outfile2.
This allows some pretty sophisticated trickery.

b) &>

stderr and stdout to file

ls -l /tmp /tmp/abc/ &>eeef

cat eeef
ls: /tmp/abc/: No such file or directory
/tmp:
total 200
-rw-r–r– 1 root   root     7709 Jul 21 09:03 aaaa
-rw-r–r– 1 root   root       99 Jul 21 09:48 bbbb
-rw-r–r– 1 root   root   176017 Jul 21 09:18 eee
-rw-r–r– 1 root   root       41 Jul 21 10:05 eeef
-rw-r–r– 1 root   root     2234 Jul 21 09:52 ewfa
-rw-r–r– 1 apache apache     10 Jul 16 08:51 myputfile.ext

 

One more question:
Why put the 2>&1 at the end of the command?

command > file 2>&1
   first of all, command > file will redirect the stdout to file,  2>&1 means stderr will copy the action of stdout, so the stderr will also be redirected to file
command 2>&1 >file
       2>&1 means stderr copy the action of stdout, but now the stdout is tty, after “>file” , the output will be redirected to file, but now the stderr still at the tty.

output by strace:
1. command > file 2>&1
open(file) == 3
dup2(3,1)
dup2(1,2)

2. command 2>&1 >file
dup2(1,2)
open(file) == 3
dup2(3,1)

References:

http://www.linuxconfig.org/Bash_scripting_Tutorial  
http://stackoverflow.com/questions/818255/in-the-bash-shell-what-is-21
http://www.cnblogs.com/caolisong/archive/2007/04/25/726896.html

Make a Comment

Leave a comment

Liked it here?
Why not try sites on the blogroll...