When you try to sort a file in-place with
sort afile > afile
you silently end up with afile
being an empty file.
Why is that? I'd expect either an error or the original contents, but sorted. I haven't tested other shells.
Upvotes for one-liners that do perform the expected behaviour.
PS bash redirect input from file back into same file doesn't address the "why" at all. I know I can go around it with a temporary file. I am interested in what happens. The upvotes for one-liners part was an afterthought in search of shorter ways.
With sort afile > afile
this happens:
The shell opens and truncates afile
because of the file direction operation > afile
The shell executes the sort
program with one argument, afile
, and binds stdout of the new process to the file descriptor opened in step 1.
The sort program opens the file given as its first argument, which is empty due to the truncation happening in step 1.
You can do it with sort afile -o afile
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With