Created
June 21, 2021 12:40
-
-
Save nil0x42/6b3af5b6781ec51a2446598aac80e682 to your computer and use it in GitHub Desktop.
atomicwrite_ifchanged (for bash automation)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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