When I type

cat some_file > new_file1 > new_file2

I got output from some_file in new_file2 and empty new_file1.

What is the inner logic in it? More specifically what is the stdout of file?

Note: On Windows the middle file is skipped.


It depends on the shell.

In bash, echo derp >file1 >file2 first opens file1, truncates it, then arranges for the stdout of echo derp to be written to file1. Then bash does the same for file2: it opens file2, truncates it, and arranges for the stdout of echo derp to be written instead to file2.

The net effect is that file1 is truncated (i.e. the content is deleted) and stdout only goes into file2. There is no chaining taking place. Bash is only capable of redirecting stdout to one place at a time. This is true for pipes as well: echo derp > file | cat results in "derp" be written to the file, not to the pipe.

In zsh, however, echo derp >file1 >file2 writes to both file1 and file2, as you might intuitively expect. See MULTIOS in man zshmisc for details if you use zsh.

To achieve this outside of zsh, you can simply use tee: echo derp | tee file1 file2 > /dev/null is equivalent to zsh's echo derp >file1 >file2.

  • +1 for teaching me tee can write to multiple files at once. For at least the bash part, file1 and file2 are created if they don't exist yet.
    – Bananguin
    Oct 12 '13 at 21:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.