bashcronfindubuntu-24.04

My cronjob to remove old data with 2 filters fails to match 1 of the filters


I am trying to create a cronjob to remove old directories (and everything within them) but skip one entire directory and any directory that ends in .save. I have tried a variety of the following find/rm job but it deletes the .save dirs. It does leave the blist/ directory intact. I've used !, -not, -prune, with and without -depth, reversed the order of blist and .save, replaced -name with -path before ".save", etc... Ubuntu 24.04

I'm testing so I'm just looking for anything older than 1 minute for now.

find test_dir/store/tmp/ -depth -type d \( ! -name "*.save" -o ! -path test_dir/store/tmp/blist \) -mmin +1 -exec rm -rf {} 2>/dev/null \;

Just focusing on the *.save part, the following command will find all the *.save directories I expect.

usr@dev9:~$ find test_dir/store/tmp/ -type d \( -name "*.save" \) -mmin +1
test_dir/store/tmp/proj3/NX3.save

But this command removes everything older than 1 minute including all *.save directories. Using '-not' instead of '!' behaves the same.

usr@dev9:~$ ls -l test_dir/store/tmp/proj3/
total 20
drwxrwxr-x 3 usr usr 4096 Nov 20 08:51 NX1
drwxrwxr-x 3 usr usr 4096 Nov 20 08:51 NX2
drwxrwxr-x 3 usr usr 4096 Nov 20 08:51 NX3
drwxrwxr-x 3 usr usr 4096 Nov 20 08:51 NX3.save
drwxrwxr-x 3 usr usr 4096 Nov 20 08:51 NX4
usr@dev9:~$ find test_dir/store/tmp/ -type d \( ! -name "*.save" \) -mmin +1  -exec rm -rf {} 2>/dev/null \;
usr@dev9:~$ ls -l test_dir/store/tmp/proj3/
ls: cannot access 'test_dir/store/tmp/proj3/': No such file or directory

Any help is appreciated.

This is a summary of my directory structure.

test_dir
└── store
    └── tmp
        ├── blist
        ├── proj1
        ├── proj2
        └── proj3
            ├── NX1
            │   └── bdata
            ├── NX2
            │   └── bdata
            ├── NX3
            │   └── bdata
            ├── NX3.save
            │   └── bdata
            └── NX4
                └── bdata

Solution

  • It looks like your command is matching on and removing the parent directories.

    -mindepth might be the flag you're looking for. From man find

           -mindepth levels
              Do not apply any tests or actions at levels less than
              levels (a non-negative integer).  Using -mindepth 1 means
              process all files except the starting-points.
    

    Copying your directory structure I used this command which I think will give you the result you're looking for (or close to it).

    find test_dir/store/tmp/ -mindepth 3 -type d \( -name "*.save" \)