Score:0

cron / crontab : auto delete oldest backup files when new files get backed up, only if disk space is near capacity

mx flag

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?

diya avatar
la flag
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`
DanRan avatar
mx flag
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.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.