Mihai Neacsu
Mihai Neacsu

Reputation: 2095

Bash ambiguous multiple redirect

For my Operating Systems class we have to implement a shell like program. I've encountered an example I don't know how to interpret:

echo "test" > out1 > out2

After running this, out1 and out2 are created but out1 is empty and out2 one contains "test".

After I launch the echo process and modify the stdout to be printed to out1, what follows next?

Upvotes: 1

Views: 103

Answers (1)

ruakh
ruakh

Reputation: 183301

The redirects are being handled from left to right: first > out1 (which creates out1 and hooks up file-descriptor #1 to it), then > out2 (which creates out2 and hooks up file-descriptor #1 to it, superseding the previous). So it's really just doing the exact same thing twice (close(1) plus fd = open(...) plus dup(fd)), just for two different files.

Edited to add: As the Bash Reference Manual puts it:

Redirections are processed in the order they appear, from left to right.

As POSIX puts it:

If more than one redirection operator is specified with a command, the order of evaluation is from beginning to end.

Of course, these explanations only apply if the redirections are really within the same simple command. Something like this:

{ echo test > out1 ; } > out2

would actually write test to out1 and leave out2 blank, because the redirection of {} occurs before echo test > out1 gets run.

Upvotes: 5

Related Questions