Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: Mixing exec redirection with explicit redirection, unexpected results

1 view
Skip to first unread message

John Reiser

unread,
Dec 8, 2009, 9:58:02 PM12/8/09
to bug-...@gnu.org
> #!/bin/bash
>
> > /tmp/foo
> exec 1>/tmp/foo
>
> echo a
> echo B>>/tmp/foo
> echo c
> echo D>>/tmp/foo
> echo e
> echo F>>/tmp/foo

That script creates two simultaneous writers of /tmp/foo
(one via the "exec >", another via each "echo >>")
but does not provide any concurrency control.
Shame on the script; the results are undefined.
The only possible legitimate complaint _might_ be
that bash did not detect and warn about the user error.

The fix is to provide some concurrency control,
or not to create multiple simultaneous writers of the same file.
Because all output is going to the same file, then the simplest
solution is to omit all the appending ">>/tmp/foo" because
they are subsumed by the initial redirection "exec >/tmp/foo".

Perhaps concurrency control can be provided by using a fifo:

mkfifo /tmp/my_fifo
cp /tmp/my_fifo /tmp/foo & # constantly drain the fifo

exec >/tmp/my_fifo
echo a
echo B >>/tmp/my_fifo

etc. However, this relies upon bash _not_ buffering
the first redirection, and that is not guaranteed.

Bottom line: avoid simultaneous writers of the same file.

--


Chet Ramey

unread,
Dec 8, 2009, 11:11:01 PM12/8/09
to ro...@enterprise.herff-jones.com, tgfu...@herffjones.com, bug-...@gnu.org, chet....@case.edu
ro...@enterprise.herff-jones.com wrote:

> When I use the 'exec' built-in to redirect standard output
> for a script, and then also use explicit redirection on
> other commands, pointing both to the same output file,
> I get unpredictable (but repeatable) results with the output
> out of order.
>
> Repeat-By:
> The following script:


>
> #!/bin/bash
>
>> /tmp/foo
> exec 1>/tmp/foo
>
> echo a
> echo B >>/tmp/foo
> echo c
> echo D >>/tmp/foo
> echo e
> echo F >>/tmp/foo
>

> ...should produce the following contents in /tmp/foo:
> a
> B
> c
> D
> e
> F
>
> ...but instead it produces:
> a
> c
> e
> F
>
>
>
> Fix:
> I am at a loss for how to understand this behavior -- sorry,
> I can't suggest a fix. :-(

It's not a bug. The important thing to remember is that the appends,
since they use a new file descriptor with a separate file offset, don't
affect the file offset associated with fd 1. Each subsequent echo
to fd 1 overwrites the previous echo that used an explicit append.

Chet
--
``The lyf so short, the craft so long to lerne.'' - Chaucer
``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, ITS, CWRU ch...@case.edu http://cnswww.cns.cwru.edu/~chet/


0 new messages