Skip to content
Advertisement

Why doesn’t “sort file1 > file1” work?

When I am trying to sort a file and save the sorted output in itself, like this

sort file1 > file1;

the contents of the file1 is getting erased altogether, whereas when i am trying to do the same with ‘tee’ command like this

sort file1 | tee file1;

it works fine [ed: “works fine” only for small files with lucky timing, will cause lost data on large ones or with unhelpful process scheduling], i.e it is overwriting the sorted output of file1 in itself and also showing it on standard output.

Can someone explain why the first case is not working?

Advertisement

Answer

It doesn’t work because ‘>’ redirection implies truncation, and to avoid keeping the whole output of sort in the memory before re-directing to the file, bash truncates and redirects output before running sort. Thus, contents of the file1 file will be truncated before sort will have a chance to read it.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement