# usage: atomicwrite_ifchanged output.txt # - overwrite atomically (mv) # - only writes to the file if new content is different # by @nil0x42 function atomicwrite_ifchanged() { test "$#" -eq 1 # ARGC == 1 test ! -t 0 # STDIN not a TTY local file="$1" local tmp_file="$(mktemp "${file}.XXXXXX.atomicwrite_ifchanged.part")" cat - >| "$tmp_file" if cmp -s "$file" "$tmp_file"; then rm "$tmp_file" else mv "$tmp_file" "$file" fi }