cmd < somefile | somefile.tmp && mv somefile.tmp somefile
Will read from somefile, and only replace the source if (and when) the pipleline exits successfully.Mind that this may still bite in interesting ways. But less frequently.
You can also invoke tempfile(1) which is strongly recommended in scripts.