[Top][All Lists]

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

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

From: Chet Ramey
Subject: Re: [Help-bash] Redirecting both stdout and stdin to a file
Date: Sun, 29 Jan 2012 21:37:40 -0500
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:8.0) Gecko/20111105 Thunderbird/8.0

On 1/28/12 6:37 PM, Davide Brini wrote:
> 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 and
>> ~$ { echo STDOUT; echo STDERR >&2; } > tmp.txt 2>&1
>> ~$ cat tmp.txt
> 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.

The keys to Davide's explanation are that redirections are associated with
commands, and that redirections are performed when a command is executed.
The left-to-right portion of the above refers to how redirections are
processed when there is more than one redirection associated with a
particular command.

When commands are executed, unless they cause the shell to fork,
redirections modify the shell's file descriptors.  (Everything is undone
when the command finishes.)  The next command executed inherits that
internal state.

The group command is the first command executed, so the redirections
associated with that command are done first.  The commands inside the
braces are executed next, and inherit that state.

``The lyf so short, the craft so long to lerne.'' - Chaucer
                 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, ITS, CWRU    address@hidden

reply via email to

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