Skip to content

Instantly share code, notes, and snippets.

@vbrozik
Last active June 11, 2021 11:44
Show Gist options
  • Save vbrozik/eaf046bcceb6e5d3db2f to your computer and use it in GitHub Desktop.
Save vbrozik/eaf046bcceb6e5d3db2f to your computer and use it in GitHub Desktop.
backup changed files - shell script
#!/bin/sh
# Copyright (c) 2015 Václav Brožík
# MIT License - See the file LICENSE.
# Description: full backup changed file(s), log operations
# Syntax: backupchanged statusfile logfile destination
datetime="$(date +%Y-%m-%dT%H:%M:%S)"
backuplist="${1-backup-list}"
logfile="${2-backup.log}"
destdir="${3-backup}/$datetime"
exec 3>>"$logfile"
mkdir "$destdir" || exit 1
printf '\n=== Backing up into %s started. ===\n' "$destdir" >&3
while read file hash size ; do
printf '%s %s - ' "$(date --rfc-3339=s)" "$file" >&3
if test -r "$file" ; then
newhash="$(md5sum -b "$file" | cut -d' ' -f1)"
newsize="$(stat -c%s "$file")"
if [ "$hash" = "$newhash" ] && [ "$size" = "$newsize" ] ; then
printf 'unchanged\n' >&3
else
printf 'newhash: %s, newsize: %s, backup ' "$newhash" "$newsize" >&3
if cp -a "$file" "$destdir" ; then
printf 'OK\n' >&3
else
printf 'FAILED\n' >&3
fi
fi
printf '%s %s %s\n' "$file" "$newhash" "$newsize" >&4
else
printf 'inacessible\n' "$file" >&3
printf '%s inacessible\n' "$file" >&4
fi
done <"$backuplist" 4>"$backuplist.new"
mv "$backuplist" "$backuplist~"
mv "$backuplist.new" "$backuplist"
if test "$(ls -a "$destdir" | wc -l)" -le 2 ; then
rmdir "$destdir"
printf 'Removed empty destination directory.\n' >&3
fi
printf '=== Backing up into %s finished. ===\n' "$destdir" >&3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment