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?
It doesn’t work because ‘>’ redirection implies truncation, and to avoid keeping the whole output of
sortin the memory before re-directing to the file, bash truncates and redirects output before runningsort. Thus, contents of thefile1file will be truncated beforesortwill have a chance to read it.