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 Answer 1


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.

  • 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, 2013 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. Oct 24, 2013 at 19:13