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
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

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


Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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

%d bloggers like this: