tags:

views:

107

answers:

5

Why is it that "sort x.txt > x.txt" clears the contents of a file while "sort x.txt > y.txt" writes the sorted file to y.txt as you would expect

+1  A: 

When you run the command, you're effectively telling the shell to open x.txt for write (>> would be append, which would be different), and then dump the results of "sort x.txt" into it - it just so happens that since it's opening the file for write, first, it effectively starts a new file with the name x.txt, and then executes sort x.txt, which sorts an empty file.

I'm not positive on the why the timing is as it is - but I believe it may keep you from trying to run a command to write to a file you don't have permission to write to, etc. (aka- it opens it for write, first, to make sure it can).

James
+1  A: 

The shell truncates x.txt before it invokes the command sort x.txt, so by the time the sort command is running, there is nothing to sort.

Just about all shells behave this way (including Windows CMD window); it is not just a feature of Cygwin.

mobrule
A: 

sort a > b open a and b together with a for reading and b for writing. as b for writing, it would be cleared.

Yin Zhu
A: 

When executing the command, first of all the shell opens the output file to write the programs output to, effectively truncating it to zero length. Then it starts the sort command, and in the sort x.txt > x.txt case this sorts the newly empty file x.txt.

sth
A: 

When the shell sees the command sort x.txt > x.txt it sees that the output of the sort command needs to go into the file x.txt, so it opens the file x.txt for writing, this will wipe out the contents of the file, if the file already had anything in it.

If you want to avoid it, you can redirect the sort output to a temp file and later rename the temp file as x.txt

codaddict