Add workable code
This commit is contained in:
parent
edc4f70c5c
commit
52e4d5825d
99
backup-if-change.sh
Normal file
99
backup-if-change.sh
Normal file
|
@ -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 "$@"
|
Loading…
Reference in a new issue