find -delete works OK, but not with cron

Solution 1:

The problem is that crontab doesn't have $PATH set when it runs. You can actually provide it with a path by adding this to the top of the file opened via crontab -e:

PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin

(or whatever PATH you'd prefer to use). This means you can avoid specifying the full paths to commands, directly from cron.

There are multiple problems with your original command. You're basically asking the shell to do the wildcard expansion, rather than find. Secondly, you're not providing a full path for rm; use /bin/rm or /usr/bin/rm, wherever it's located on your system (see which rm).

The first argument for find is the "location to search", and then you specify the "search query" with the various -<option>s. So, the proper format of the command you want to run is:

find "/home/bkp/dbdump" -name "*.gz" -mtime +5 -exec rm -f {} \;

or

find "/home/bkp/dbdump" -name "*.gz" -mtime +5 delete

If you don't specify the PATH definition like above, use:

/usr/bin/find "/home/bkp/dbdump" -name "*.gz" -mtime +5 -exec /bin/rm -f {} \;

or

/usr/bin/find "/home/bkp/dbdump" -name "*.gz" -mtime +5 delete

Solution 2:

Try this instead

find /home/bkp/dbdump -type f -name '*.gz' -mtime +5 -delete

Tags:

Cron