bug-bash
[Top][All Lists]
Advanced

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

Re: order of redirections


From: Bob Proulx
Subject: Re: order of redirections
Date: Mon, 2 Mar 2009 16:08:01 -0700
User-agent: Mutt/1.5.13 (2006-08-11)

lehe wrote:
> I have some questions about the paragraph in Bash Reference on redirections:
> "Note that the order of redirections is significant. For example, the
> ...
>       ls > dirlist 2>&1
> directs both standard output (file descriptor 1) and standard error (file
> descriptor 2) to the
> file dirlist, while the command
>       ls 2>&1 > dirlist
> directs only the standard output to file dirlist, because the standard error
> was duplicated
> as standard output before the standard output was redirected to dirlist."
> 
> In the first example "ls > dirlist 2>&1", does it mean first "ls > dirlist"
> and then "2>&1"?

Not "ls >dirlist" but ">dirlist".  ">dirlist" is the first redirection
and "2>&1" is the second.  The order of those two operations is
significant and the behavior different if reversed.

> If yes, then dirlist will not have the content of standard
> error 2.

I read that question/statement several times but I couldn't quite tell
what you meant by it.  Sorry.

If ls encounters an error it will print the error to standard error.
If you want both the standard output and the standard error to be
redirected synchronously to the same file then you want the following:

  ls >SOMEFILE 2>&1

Doing so in a different order such as "ls 2>&1 >SOMEFILE" does
something different.

> In the second example "ls 2>&1 >dirlist", does it mean "ls 2>&1" and then
> ">dirlist" where 1 is omit as default before >?

Not "ls 2>&1" but "2>&1".  "2>&1" is first and ">dirlist" is second.
The file descriptor is omited but taken as the default value 1.
">FILE" is the same as "1>FILE" and the typical idiom is to use
">FILE" in that case.

A way to think about this ordering issue is to consider that the shell
holds the file descriptors in program variables.  These variables are
assigned in the order seen on the command line from left to right.
The following pseudo code isn't from the actual shell code but perhaps
thinking of it this way will help model it for you.

  ">FILE 2>&1"  # Redirects both stdout and stderr to FILE.
    1>FILE      #  fd[1] = open_for_reading(FILE)
    2>&1        #  fd[2] = fd[1]

  "2>&1 >FILE"  # Redirects stderr.  Redirects stdout to file.
    2>&1        #  fd[2] = fd[1]
    1>FILE      #  fd[1] = open_for_reading(FILE)

In the second case it should now be apparent that the stderr isn't
associated with FILE because of the ordering.

Bob




reply via email to

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