Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@CristianCantoro
Last active February 9, 2018 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CristianCantoro/8cc103ef90c6a257f5eed365c7832da2 to your computer and use it in GitHub Desktop.
Save CristianCantoro/8cc103ef90c6a257f5eed365c7832da2 to your computer and use it in GitHub Desktop.
Backup script for restic
#!/usr/bin/env bash
# shellcheck disable=SC2128
SOURCED=false && [ "$0" = "$BASH_SOURCE" ] || SOURCED=true
if ! $SOURCED; then
set -euo pipefail
IFS=$'\n\t'
fi
awk_script=$(cat <<'AWKSCRIPT'
BEGIN { RS="(\r|\n)";
FS="";
}
{
printf "[" strftime("%Y-%m-%d %H:%M:%S") "]: ";
printf $0;
if (RT=="\r") {
printf "\r";
} else {
printf "\n";
}
}
AWKSCRIPT
)
OLDIFS="$IFS"
IFS='' awk_script=$(echo "$awk_script" | tr '\t' ' ' | tr '\n' ' ')
IFS="$OLDIFS"
LOGFILE='/var/log/backup/restic.log'
#################### functions
function log() {
echo "$1" | awk '{print "[" strftime("%Y-%m-%d %H:%M:%S") "]: " $0 }' | \
sudo tee -a "$LOGFILE"
return 0
}
##############################################################################
log 'Start'
# shellcheck disable=SC1090
source "$HOME/.restic/environment"
if [ -z "$RESTIC_REPOSITORY" ] || [ -z "$RESTIC_PASSWORD_FILE" ]; then
(>&2 echo 'RESTIC_REPOSITORY or RESTIC_PASSWORD_FILE not set. Abort.' )
exit 1
fi
if [ ! -d "$RESTIC_REPOSITORY" ]; then
(>&2 echo 'RESTIC_REPOSITORY is not a directory. Abort.' )
exit 2
fi
sudo mkdir -p '/var/log/backup/'
sudo touch "$LOGFILE"
log 'Backing up...'
sudo -EH stdbuf -o0 restic backup \
--exclude-file "$RESTIC_EXCLUDES_FILE" \
"$RESTIC_BACKUP_TARGET" 2>&1 | \
stdbuf -o0 awk "$awk_script" | \
sudo tee -a "$LOGFILE"
log 'Backup complete'
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment