Skip to content

Instantly share code, notes, and snippets.

@nil0x42
Created June 21, 2021 12:40
Show Gist options
  • Save nil0x42/6b3af5b6781ec51a2446598aac80e682 to your computer and use it in GitHub Desktop.
Save nil0x42/6b3af5b6781ec51a2446598aac80e682 to your computer and use it in GitHub Desktop.
atomicwrite_ifchanged (for bash automation)
# 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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment