Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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.

share|improve this answer
    
+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
    
Thanks, I'm mostly interested in bash. –  jnovacho Oct 13 '13 at 10:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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