File in-place editing with tee behaving differently on different unixes
A coworker was experimenting with file truncation in a bash shell script: extract two first bytes out of a binary file.
The following worked fine on BSD/OS X ("12" in output) but not on Linux (output was empty):
echo 1234 >test
head -c2 test | tee test >/dev/null
Changing the head | tee
part to run in a subshell
echo 1234 >test
(head -c2 test | tee test >/dev/null)
made it work on Linux as well.
Why?
(Specifically not interested in solutions to the truncating problem but an explanation why the behavior is different on different flavors of operating sy开发者_如何学JAVAstems.)
tee
opens its arguments for writing, truncating them in the process, but whether head
or tee
opens the file first is left to chance. Either behavior is valid; you just shouldn't rely on this mini-script doing anything useful.
精彩评论