Opinion on an easy shell script (mv)

:wall:I've this simple code:

STF=/opt/aaa
cat $STF | nice sort -u > $STF.new && mv $STF.new $STF

Which works until today. What happened is that this script has been corrupted the FS, so I've to use fschk to repair the filesystem.

I presume the move command executed just a little too early so it corrupted the FS, so I modified the code like this:

STF=/opt/aaa
cat $STF | nice sort -u > $STF.new 
sleep 1
mv $STF.new $STF

Which does the job and works. What I ask you is there another "safe" way to rename a file? Your thoughts/opinions?

I don't think that script corrupted the FS, as the mv command is executed only when the cat | sort pipe has finished (only then the exit code is available!), and mv doesn't do anything but a rename, i.e. changing the directory entry, not fiddling around with file data nor inode metadata.