0

I am using crontab (on Ubuntu Server 20.04) to automatically create daily backups of a text file and storing them on an external hard drive. I am using the following crontab to create my backups:

@daily cp ~/myfile.txt /mnt/usb/backups/$(date +\%Y\-\%m\-\%d)_myfile.txt

This effectively creates a daily backup file on my external hard drive with the date and time (year/month/day) of creation prefaced in the filename. i.e. /mnt/usb/backups/2023-02-01_myfile.txt and /mnt/usb/backups/2023-02-02_myfile.txt etc.

The problem is that the hard drive is eventually going to fill up. So what I want to do is automatically delete the oldest version of the backup image file (but only delete when external HD space is running out) every time the cp backup command runs in crontab. This would prevent the external drive from filling up by deleting the oldest version of the backed up file when the disk space is near capacity.

Does anyone have any idea how I might go about doing this?

DanRan
  • 73
  • 1
  • 3
  • 22
  • Create a script in your favourite scripting language that applies the logic you need and does what you need and replace the cron job `@daily cp ~ ...` with `@daily /path/to/script` - i.e. `check if /mnt/usb/backups is mounted` if true `check %used` if too full `first do clean up` then `make make up` if error(s) `send notification` else `log success` and `EXIT` – diya Feb 02 '23 at 12:00
  • Thans for the reply @diya . But my problem is that I don't really know how to write scripts, let alone for these circumstances. I was hoping for an answer that would provide an example script that I could use. – DanRan Feb 04 '23 at 18:44

0 Answers0