Reputation: 573
I know 0 , 1, 2 are STDIN , STDOUT and STDERR file descriptors. I am trying to understand redirection. '>' means dump to a file '>>' means append
But what does '>&' do ? Also what is the step by step process for the following commands ?
command > file 2>&1
command > file 2<&1
Upvotes: 1
Views: 198
Reputation: 15783
NUMBER1>&NUMBER2
means to assign the file descriptor NUMBER2 the file descriptor NUMBER1.
That means, to execute dup2 (NUMBER2, NUMBER1)
.
command > file 2>&1
Bash process the command line, it finds first the redirection >file
, it changes stdout to be written to file
, then continue to process and finds 2>&1
, and changes stderr to be written to stdout (which is file
in this moment) .
command > file 2<&1
this is the same, but 2<&1
redirects stderr to read
from stdout. Because nobody reads from stderr, this second redirection normally has no effect.
However, bash treats this special case doing the same as for 2>&1
, so executing dup2 (1, 2)
.
What does "2<&1" redirect do in Bourne shell?
Upvotes: 4
Reputation: 154836
Let's analyze it step by step:
>place
means reopen the standard output so that it begins writing to place
, which is a file name that will be open for writing. This is the typical redirection.
N>place
does the same for an arbitrary file descriptor n. For example, 2>place
redirects the standard error, file descriptor 2, to place
. 1>place
is the same as >place
.
If place is written with the special syntax &N
, it will be treated as an existing file descriptor number rather than a file name. So, >&2
and 1>&2
both mean reopen the standard output to write to standard error, and 2>&1
is the other way around.
The exact same goes for input, except place and the descriptors are opened for reading, and the file descriptor left of the <
sign defaults to 0, which stands for standard input. 2<&1
means "reopen file descriptor 2 for reading so that future reads from it actually read from file descriptor 1". This doesn't make sense in a normal program since both file descriptors 1 and 2 are open for writing.
Upvotes: 5
Reputation: 17312
2>&1
means redirect STDERR
to the same place that STDOUT
is going to. One example where it's useful is grep
which normally works on STDOUT
this makes it work on STDOUT
and STDERR
:
app 2>&1 | grep hello
Upvotes: 1