From 52e4d5825d7b6beb0068cbaa89e80165f55fc888 Mon Sep 17 00:00:00 2001 From: leafee98 Date: Thu, 22 Dec 2022 16:46:17 +0800 Subject: [PATCH] Add workable code --- backup-if-change.sh | 99 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 backup-if-change.sh diff --git a/backup-if-change.sh b/backup-if-change.sh new file mode 100644 index 0000000..32a6138 --- /dev/null +++ b/backup-if-change.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash + +set -o errexit +set -o errtrace +set -o nounset + +function trap_err() +{ + echo Exiting because error occurred in script. +} +trap trap_err ERR + + +HASH_TOOL="sha256sum" +INTERNEL=32 +TARGET_DIR="" +FILE="" + + +function show_usage() +{ + echo "$0 usage:" + echo " --target-dir Directory to store the backup files" + echo " --file The file to monitor" + echo " --hash-tool Tools to calculate hash of file, default sha256sum" + echo " --internel Seconds between checking file, default 32s" +} + +function my_log() +{ + echo "$(date --iso-8601=ns) -- $*" +} + +function backup_the_file() +{ + local the_file=$1 + local target="${the_file}_$(date --iso-8601=seconds --reference $the_file)" + my_log "backuping the file to $target" + + if [ -f "$TARGET_DIR/$target" ] + then + my_log "$target already exists, skipped." + else + cp --no-target-directory $the_file $TARGET_DIR/$target + fi +} + + +function main() +{ + while [ "$#" -gt 1 ] + do + case "$1" in + "--target-dir") + TARGET_DIR=$2 + shift + ;; + "--file") + FILE=$2 + shift + ;; + "--hash-tool") + HASH_TOOL=$2 + shift + ;; + "--internel") + INTERNEL=$2 + shift + ;; + *) + echo unknown option: $1 + show_usage + exit 1 + ;; + esac + shift + done + + if [ -z "$FILE" -o -z "$TARGET_DIR" ] + then + echo "option(s) --file or --target-dir is unspecified." + exit 1 + fi + hash_prev="" + while [ "true" ] + do + hash_curr=$(eval "$HASH_TOOL $FILE") + if [ "$hash_prev" != "$hash_curr" ] + then + my_log "the hash now: $hash_curr" + backup_the_file $FILE + hash_prev=$hash_curr + fi + + sleep "$INTERNEL" + done +} + +main "$@"