1

Please explain the output of this shell command:

ls >file1 >file2

Why does the output go to file2 instead of file1?

crisron
  • 363
  • 2
  • 5
  • 21

5 Answers5

4

bash only allows one redirection per file descriptor. If multiple redirections are provided, like in your example, they are processed from left to right, with the last one being the only one that takes effect. (Notice, though, that each file will still be created, or truncated if already in existence; the others just won't be used by the process.)

Some shells (like zsh) have an option to allow multiple redirections. In bash, you can simulate this with a series of calls to tee:

ls | tee file1 file2 > /dev/null

Each call to tee writes its input to the named file(s) and its standard output.

chepner
  • 497,756
  • 71
  • 530
  • 681
2

If the shell finds multiple redirections of any output, it will redirect it to the last file given, in your case file2, since redirections are evaluated from left to right.

While it works, you should not do something like that!

Mithrandir
  • 24,869
  • 6
  • 50
  • 66
1

The redirect operator is short for a stdout redirection(1>). Since the command is evaluated left to right, the last stdout redirection is used for the running of ls.

ls 1> file1 1>file2 

is equivalent to

ls >file1 >file2

If you're trying to redirection stderr, use

ls > file1 2> file2

0 = stdin
1 = stdout
2 = stderr

try this, you'll notice that file2 will receive the stderr message.

ls ------ > file1 2> file2

then these, in both cases output will be in stdout and will go to file1.

ls >file1 2>file2
ls 1>file1 2>file2
JustinDanielson
  • 3,155
  • 1
  • 19
  • 26
0

You first redirected the STDOUT stream to go to file1 but then immediately redirected it to go to file2. So, the output goes to file2.

Every process initially has three file descriptors - 0 for STDIN, 1 for STDOUT and 2 for STDERR. >file1 means that open the file1 and assign its descriptor the id 1. Note that the process which is about to execute doesn't care about what is the end point where its STDOUT goes. It just writes to whatever is described by file descriptor 1.

For a more technical description of how this works, see this answer.

Community
  • 1
  • 1
Chandranshu
  • 3,669
  • 3
  • 20
  • 37
  • I got a downvote after 2 upvotes when I was the first one to answer. I think this needs to be flagged for the moderators. – Chandranshu Nov 19 '13 at 21:03
0

Because first redirection gets overridden by the second. Note though, that an empty file1 is still created when file1 was opened for output.

Logan Lee
  • 807
  • 9
  • 21