Skip to content

Instantly share code, notes, and snippets.

@mttjohnson
Created April 7, 2022 15:05
Show Gist options
  • Save mttjohnson/10533744c817ddea0fc71b94c2426ac6 to your computer and use it in GitHub Desktop.
Save mttjohnson/10533744c817ddea0fc71b94c2426ac6 to your computer and use it in GitHub Desktop.
file backup script
#!/usr/bin/env bash
# Simple file backup script
# This can be easily put into a cron job to automatically maintain a rolling 7 day backup of specified
# paths tarred and gzipped accessible to the user running the script.
#
# Usage:
# filebackup.sh <backup_name> <directory_to_backup> <backup_storage_directory>
#
# Reference: https://github.com/classyllama/ansible-role-filebackup/blob/master/templates/filebackup.sh.j2
set -e
# Set variables
BACKUP_NAME=""
DIRECTORY_TO_BACKUP=""
BACKUP_STORAGE_DIRECTORY=""
FILE_TO_BACKUP=""
[ -n "$1" ] && BACKUP_NAME=$1
[ -n "$2" ] && DIRECTORY_TO_BACKUP=$2
[ -n "$3" ] && BACKUP_STORAGE_DIRECTORY=$3
[ -n "$4" ] && FILE_TO_BACKUP=$4
TIMESTAMP=$(date --utc +%Y%m%dT%H%M%SZ) # Get ISO 8601 UTC Timestamp
# Set default file permissions 600
umask 177
# Make sure backup storage directory exists
mkdir -p ${BACKUP_STORAGE_DIRECTORY}
# Create archive file of directory (storing relative paths inside archive)
tar -czf ${BACKUP_STORAGE_DIRECTORY}/${BACKUP_NAME}_${TIMESTAMP}.tar.gz -C ${DIRECTORY_TO_BACKUP} ./${FILE_TO_BACKUP}
# Delete files older than 7 days
find ${BACKUP_STORAGE_DIRECTORY}/${BACKUP_NAME}_* -mtime +7 -exec rm {} \;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment