I'm writing a command for cron to do automatic backups for my flashdrive.
I use tar ... -N <some date> to make the backup.
The issue is how to write the command which gives me the right date.

For weekly backup I thought about:
date -d '1 week ago' +%Y%m%d
date -d 'monday week ago' +%Y%m%d

But it gets complicated when when my laptop is turned off on the cron scheduled time (monday after). Let's say anacron pick up the job on Tuesday. With the first variant I miss all changes from previous Monday. The second variant misses the whole previous week.
date -d 'monday 1 week ago' +%Y%m%d is the same as date -d 'monday week ago' +%Y%m%d
date -d 'monday 2 week ago' +%Y%m%d is correct in the case when backup is made by anacron, but it has one week extra in (the regular case) of cron.

Any idea, how could I make the backup time anacron compatible?

1 Answer 1


Here's an idea: Every time a backup is run, the backup script records the current date by touching a file. The next time the backup runs, it uses the previous backup's datestamp file as the argument to tar -N. For example, in a shell script, the logic could look like this:

# Begin the latest backup run now.
touch /backups/new-backup-time

tar -N /backups/prev-backup-time -c ... ...

# Save the latest backup time for the next run.
mv /backups/new-backup-time /backups/prev-backup-time

This depends on the fact that the tar -N option can either be a date, OR it can be the pathname of a file whose data modification time specifies the date.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.