2

prova1 is a file with some text. When I run this code prova1 become empty:

sort prova1 > prova1

I know that to achieve the effect I can do:

sort prova1 -o prova1

I would just know the reason :)

1 Answers1

6

This is because the redirection is carried out first: >prova1 truncates your file so that the sort finds nothing. sort prova1 > prova1_sorted would work as you expect.

Joseph R.
  • 39,549
  • 2
    It might be worth noting that sort's -o option probably works around this by creating a temporary file, the same as sed's -i option. – evilsoup Oct 24 '13 at 17:19
  • 2
    Depends. If sort is sorting in memory, it has to read the whole file to memory before writing anyway. If it's using some kind of merge sort with files it might need more than one temp file, independantly of the output. – Michael Suelmann Oct 24 '13 at 19:13