3 ms·
The "ls >output" example exposes a subtle artifact of the implementation: the output file will contain its own name.
by userbinator 6y ago
The "ls >output" example exposes a subtle artifact of the implementation: the output file will contain its own name.
- codetrotter 6y agoIt’s not really subtle I think. When you redirect to a file, the file is opened for writing by the shell before it runs the program that you are invoking. This is also the same reason that if you try something like the following: grep whatever somefile >somefile You always end up with somefile being empty, whereas what you thought you were doing was replacing the contents of the file with only the lines in the file that contain the word “whatever”. But instead the shell will truncate the file first and then grep is searching through an already empty file and therefore there is nothing to find and the file ends up empty.
- rootbear 6y agoBack in my BSD-on-a-VAX days, I once typed grep string * > out and wondered why it was taking so long. The shell (probably csh) had created the file "out" before it expanded the *, so my grep command was forever finding "string" in it's own output. It filled the disk before I realized what was happening. I just did a quick test and bash seems to create the output file after doing the globbing, and under tcsh, grep gave a warning that the output file was also an input file and it did not search it.