Subject: bug#47883: sort -o loses data when it crashes

From: Paul Eggert <[email-masked]>
Date: Wed, 21 Apr 2021 19:11:14 -0700

On 4/18/21 10:46 AM, Peter van Dijk wrote:
> While the manual (but not the manpage) mentions the data loss, I think it would be great if sort did not have this problem at all, and I think the OpenGroup text also says it should not have this problem.

I don't know of any 'sort' implementation that does not have the problem 
at all. For example, FreeBSD 'sort -o file file' can lose 'file' in some 
(rare) cases. The only portable way to avoid this problem in a shell 
script is to output to some other file first and make sure that worked, 
before attempting to replace the input file.

Also, I don't see where the Open Group spec says what you're saying. On 
the contrary, the spec merely says that '-o output' should cause output 
to be sent to the output file. If there are multiple hard links to the 
output file, this suggests 'sort' should update the output file's 
contents without breaking any hard links. Admittedly the Open Group spec 
is a bit vague in this area, but I certainly don't see anything implying 
that GNU 'sort' does not conform to POSIX in this area.

FreeBSD 'sort' has a problem, in that 'sort -o A B' preserves all hard 
links to A's file, but 'sort -o A A' does not because it breaks the link 
from A. That's confusing.

Traditional Unix 'sort -o A' behaves the way GNU 'sort' does; it 
preserves all hard links to A's file. So there is a compatibility 
argument for doing things the way GNU 'sort' does them, even if that 
might lead to more data loss in rare cases.