help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Redirecting both stdout and stdin to a file


From: Davide Brini
Subject: Re: [Help-bash] Redirecting both stdout and stdin to a file
Date: Sun, 29 Jan 2012 00:37:00 +0100

On Sat, 28 Jan 2012 16:15:59 -0600, Peng Yu <address@hidden> wrote:

> Hi,
> 
> Recent, there were some discussion on I/O redirection. But I still
> don't think that I fully understand it. I created the following
> example, only the first one can direct both stdout and stdin to a
> file. But the second one can not.
> 
> To quote recent Chet's email "Redirections are processed left to right
> (or, in the Posix parlance, `beginning to end')". What appears to be
> in the following example is like from right to left.
> 
> There must be some rule that I missed. Could anybody let me know how
> to understand the difference between the two commands?

Please read http://wiki.bash-hackers.org/howto/redirection_tutorial and
http://mywiki.wooledge.org/BashFAQ/055.

> ~$ { echo STDOUT; echo STDERR >&2; } > tmp.txt 2>&1
> ~$ cat tmp.txt
> STDOUT
> STDERR

The code inside braces would output STDOUT to fd 1 and STDERR to fd 2. At
this point, both fd 1 and fd 2 (and fd 0, for that matter) are connected to
the terminal (for example, /dev/pts/1, or whatever).

The first external redirection changes this, and directs fd 1 to
"tmp.txt" (because "> tmp.txt" is equivalent to "1> tmp.txt", if that's any
clearer). Once that is done, the second external redirection changes
fd 2 too, and connects it to the same object to which fd 1 points
which, as we've just seen, is now the file "tmp.txt". The result is that
both STDOUT and STDERR end up in the file.

> ~$ { echo STDOUT; echo STDERR >&2; } 2>&1 > tmp.txt
> STDERR
> ~$ cat tmp.txt
> STDOUT

Here the initial situation is the same as before (fd 1 and fd 2 connected
to the terminal). However the first external redirection directs fd 2 to the
same object to which fd 1 points, which at this point is still the
terminal. From now on, fd 2 points to the terminal (ie, just like before the
redirection). The second redirection redirects fd 1 from the terminal to the
file "tmp.txt". After all is done, fd 1 points to the file, and fd 2 points
to the terminal. Hence, STDOUT (which is output to fd 1) ends up in the
file, and STDERR (which was output to fd 2) ends up in the terminal.

-- 
D.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]