Understanding Shell Script's idiom: 2>&1
And a quick introduction to file descriptors
A file descriptor is nothing more that a positive integer that represents an open file. If you have 100 open files, you will have 100 file descriptors for them.
The only caveat is that, in Unix systems, everything is a file. But that's not really important now, we just need to know that there are file descriptors for the Standard Output (stdout
) and Standard Error (stderr
).
In plain English, it means that there are "ids" that identify these two locations, and it will always be 1
for stdout
and 2
for stderr
.
Putting the pieces together
Going back to our first example, when we redirected the output of cat foo.txt
to output.txt
, we could rewrite the command like this:
$ cat foo.txt 1> output.txt
This 1
is just the file descriptor for stdout
. The syntax for redirecting is [FILE_DESCRIPTOR]>
, leaving the file descriptor out is just a shortcut to 1>
.
So, to redirect stderr
, it should be just a matter of adding the right file descriptor in place:
# Using stderr file descriptor (2) to redirect the errors to a file $ cat nop.txt 2> error.txt $ cat error.txt cat: nop.txt: No such file or directory
At this point you probably already know what the 2>&1
idiom is doing, but let's make it official.
You use &1
to reference the value of the file descriptor 1 (stdout
). So when you use 2>&1
you are basically saying "Redirect the stderr
to the same place we are redirecting the stdout
". And that's why we can do something like this to redirect both stdout
and stderr
to the same place:
Read full article from Understanding Shell Script's idiom: 2>&1
No comments:
Post a Comment