0

Situation: When using the following command:

cat foo | sort | tee foo

where foo is a text file of multiple lines, the outcome is not consistent. The two outcomes I've observed are:

  1. The file is sorted, and the sorted contents are printed to stdout.
  2. The file is emptied, and nothing is printed.

Question: Why does this happen?

P.S. I realize that sort has a -o option on my system.

marked as duplicate by terdon bash Dec 28 '17 at 8:59

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

0

You create a race condition. You start two commands (on both sides of the pipeline) which both try to access the same file in different ways (read vs. erase). The result is chance.

cat foo | sort | ( tee foo.new; mv foo.new foo)

Not the answer you're looking for? Browse other questions tagged or ask your own question.