This post contains code that will enable you to automatically backup a directory and remove backups older than 3 weeks.

The following Bash script is a cronjob directory backup script that takes two arguments:

  1. the folder to backup
  2. the output directory

It will also automatically clean up any backups that are more than 3 weeks old.

See below.

The backup script

#!/bin/bash -e

outputtargz=$(basename "${2}" .tar.gz)
tgtpath=$(dirname "${2}")

output="${tgtpath}/${outputtargz}__$(date +%m-%d-%y_%H-%M).tar.gz"

mkdir -p "${tgtpath}"
tar -czvf "${output}" "${1}"

# Clean up any old files (3 weeks or older)
find "${tgtpath}/*" -mtime +21 -type f -delete

echo "Backed up ${1} to ${output} successfully"

Usage

It can be used like this:

./backup_script.sh /path/to/backup /target/location

Cronjob: Automated backups

It can also be used as a cronjob. To edit your crontab, use the command:

crontab -e

You may need to run the crontab -e command with sudo if your backup source or target is not readable by the current user.

Here’s an example cronjob that runs every 6 hours at 12am, 6am, 12pm, and 6pm:

# Install this as a cronjob:
SHELL=/bin/bash
0 0,6,12,18 * * * /path/to/this/backup_script.sh /home/my/folder1 /mnt/backups/folder1.tar.gz

Final note

For help with crontab job intervals, use the handy website crontab.guru.

This can be used on Ubuntu, Linux Mint, Arch Linux, or any other Linux OS/environment that supports running bash and shell scripts natively.