0

I have a doubt about a simple command and it is because in bash if I do

sort file.txt > file.txt

file .txt remains empty (it shouldn't keep file.txt with what it had before but sorted) but if I do

sort file.txt >> file.txt

then the ordered elements are added to the previous elements.

Gedeon Mutshipayi
  • 2,871
  • 3
  • 21
  • 42
  • duplicates: [why does this blank the file?](https://stackoverflow.com/q/16634207/995714), [Why does redirecting the output of a file to itself produce a blank file?](https://superuser.com/q/597244/241386), [How can I use a file in a command and redirect output to the same file without truncating it?](https://stackoverflow.com/q/6696842/995714), [Why redirecting output sometimes produces an empty file?](https://unix.stackexchange.com/q/586443/44425), [Why is the file being emptied during input/output redirection to the same file?](https://askubuntu.com/q/1289971/253474) – phuclv Apr 23 '22 at 16:10

2 Answers2

1

As soon as you targeted your file with > the shell truncated all the data before sort could read it.

sort file.txt > tmp.txt && mv tmp.txt file.txt 
Paul Hodges
  • 13,382
  • 1
  • 17
  • 36
1

This is the expected behavior. The phrase > file.txt opens file.txt for overwriting before the command sort is even run. So when sort runs it sees that file.txt is empty.

On the other hand, the phrase >> file.txt opens file.txt for appending before the command sort is even run. So when sort runs it reads the full file and then appends the results to the file.

dg99
  • 5,456
  • 3
  • 37
  • 49