Skip to content

Instantly share code, notes, and snippets.

@jasontbradshaw
Last active December 28, 2021 12:56
Show Gist options
  • Save jasontbradshaw/c2f9c089773e5c7af5fc to your computer and use it in GitHub Desktop.
Save jasontbradshaw/c2f9c089773e5c7af5fc to your computer and use it in GitHub Desktop.
A simple backup script using tar.
#!/usr/bin/env sh
# arguments
name="${1}"
src="${2}"
dest_dir="$(dirname "${3}/gets_removed")"
# validate arguments
if [ -z "${name}" ]; then
echo "Invalid backup name (first argument)"
exit 1
elif [ ! -d "${src}" ]; then
echo "Invalid source directory: '${src}'"
exit 1
elif [ ! -d "${dest_dir}" ]; then
echo "Invalid destination directory: '${dest_dir}'"
exit 1
fi
suffix='.tar.gz'
temp_prefix="${dest_dir}/${name}-incomplete-backup-"
temp_dest="${temp_prefix}$(date --utc '+%FT%R:%SZ')${suffix}"
dest="${dest_dir}/${name}-backup${suffix}"
# use pigz if possible, otherwise default to gzip
compression_prog="gzip"
if which pigz > /dev/null 2>&1; then
# multicore gzip replacement
compression_prog="pigz"
fi
echo "Backing up to ${temp_dest}"
echo "Using ${compression_prog} for compression"
# do the backup as non-intrusively as possible
nice -n19 ionice -c3 tar \
--verbose \
--sort="name" \
--preserve-permissions \
--ignore-failed-read \
--exclude="/dev/*" \
--exclude="/proc/*" \
--exclude="/sys/*" \
--exclude="/tmp/*" \
--exclude="/run/*" \
--exclude="/mnt/*" \
--exclude="/media/*" \
--exclude="/lost+found/*" \
--exclude="/home/*/.cache/*" \
--exclude="/home/*/.config/*chrom*/Default/File System/*" \
--exclude="/home/*/.config/*chrom*/Default/GPUCache/*" \
--exclude="/home/*/.dropbox/logs/*" \
--exclude="/home/*/.local/share/Trash/*" \
--exclude="/home/*/.mozilla/firefox/*/Cache" \
--exclude="/home/*/.gvfs" \
--exclude="/home/*/.thumbnails/*" \
--exclude="${temp_dest}" \
--exclude="${dest}" \
--exclude-backups \
--exclude-caches \
--one-file-system \
--use-compress-program="${compression_prog}" \
--create \
--file="${temp_dest}" \
"${src}"
# if the backup succeeded, replace the old one with the temp version
if [ "$?" -eq 0 ]; then
echo "Moving ${temp_dest} to ${dest}"
mv "${temp_dest}" "${dest}"
# remove any old incomplete backups with an identical prefix
echo "Removing expired incomplete backups..."
rm -f ${temp_prefix}*${suffix}
echo "Backup to ${dest} complete!"
else
echo "Backup to ${temp_dest} failed (code $?)!"
exit "$?"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment