0

I got a directory structure like this:

/backups/
/backups/db/
/backups/db/01.01.2020/domain_a.sql.gz, domain_b.sql.gz, domain_c.sql.gz
/backups/db/02.01.2020/domain_a.sql.gz, domain_b.sql.gz, domain_c.sql.gz
/backups/db/03.01.2020/domain_a.sql.gz, domain_b.sql.gz, domain_c.sql.gz
/backups/db/04.01.2020/domain_a.sql.gz, domain_b.sql.gz, domain_c.sql.gz

Now Im running this command:

find /backups/db/ -mindepth 1 -mtime +2 -delete && rsync ...

When I execute this command directly in the shell, it works and the result is:

/backups/
/backups/db/
/backups/db/03.01.2020/domain_a.sql.gz, domain_b.sql.gz, domain_c.sql.gz
/backups/db/04.01.2020/domain_a.sql.gz, domain_b.sql.gz, domain_c.sql.gz

If I run this command by a cronjob, the directories wont be deleted and the result is:

/backups/
/backups/db/
/backups/db/01.01.2020/
/backups/db/02.01.2020/
/backups/db/03.01.2020/domain_a.sql.gz, domain_b.sql.gz, domain_c.sql.gz
/backups/db/04.01.2020/domain_a.sql.gz, domain_b.sql.gz, domain_c.sql.gz

This happens cause find first delete the files within these (2) folders and this action change the date of these folders, so that they dont match anymore the -mtime +2.

Is there any solution? I mean I could go with something like this, but I usually dont like to work with rm if its not necessary.

find /backups/db/ -mindepth 1 -mtime +6 -type d -exec rm -r {} +

find (GNU findutils) 4.7.0-git

0

I would suggest that you do this in two steps, and that you only delete files in the first step:

find /backups/db -mindepth 1 -type f -mtime +2 -delete

Then delete empty directories:

find /backups/db -mindepth 1 -type d -empty -delete

This way you don't compare timestamps on directories at all.

You could possibly combine the two operations into

find /backups/db -mindepth 1 \
    \( \( -type f -mtime +2 \) -o \
       \( -type d -empty    \) \) -delete

... but you may want to check without -delete that it does the correct thing first.

1
  • Thanks for the suggestion. I think I go with find /backups/db -mindepth 1 -type f -mtime +2 -delete && find /backups/db -mindepth 1 -type d -empty -delete. But I will also checkout the combined version. :) – Kuba Oct 20 '20 at 13:32

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.