1

I have a very simple bash script that runs flawlessly when I do

./removeOldBackup.sh

or

sh /home/myusername/backup/removeOldBackup.sh

but when I add it to crontab like

* * * * * sh /home/myusername/backup/removeOldBackup.sh

or

* * * * * /bin/sh /home/myusername/backup/removeOldBackup.sh

it never works...

This is my script:

#!/bin/sh

find . -name 'files_20[1-3][0-9]-[0-9][0-9]-[1-2][1-9]--*' -delete
find . -name 'files_20[1-3][0-9]-[0-9][0-9]-0[2-9]--*' -delete

find . -name 'database_20[1-3][0-9]-[0-9][0-9]-[1-2][1-9]--*' -delete
find . -name 'database_20[1-3][0-9]-[0-9][0-9]-0[2-9]--*' -delete

This is my script permissions:

-rwxr-xr-x 1 root root 295 Jul 25 10:07 /home/myusername/backup/removeOldBackup.sh

Crontab is added for user root.

This is what I find in /var/log/syslog:

Jul 25 10:11:01 myservername /USR/SBIN/CRON[7583]: (root) CMD (sh /home/myusername/backup/removeOldBackup.sh)

So again, when I run the script manually, my backup files get removed correctly. When it is run by cron, they never get removed. I'm using debian-6.0-x86_64.

polym
  • 10,852
borsuk
  • 113
  • 1
    Your find runs on current working directory ie. when you run your script as ./script.sh, everything works fine. However, when cron runs your script, the current working directory is not what you expect it to be. Add cd /correct/path in the beginning of your script or use an absolute path for find. –  Jul 25 '14 at 08:43
  • I tried to find an answer here on stackexchange as well as googling but didn't think the path might be the reason. I just thought the script doesn't run at all. Thank you both for help. – borsuk Jul 25 '14 at 11:28

1 Answers1

1

To formalise and expand on what someone said in a comment, when you put something in root's crontab it will run inside /root, not in the directory the script is in, because cron doesn't even know where that is. Because your backup files aren't in that directory tree, the find command never reaches them. So the job is running, it just never finds any files to delete. Providing an absolute path to find or adding cd /home/myusername/backup first will fix your problem.

Nonetheless, there doesn't seem to be a need to run this cronjob as root at all: all the files are inside myusername's home directory and presumably owned by them too. Why not put your cronjob inside that user's crontab instead? Run crontab -e as myusername and add the exact same line you used for root's version. That way you aren't needlessly running a task as a privileged user (which automatically deletes files, no less), and you'll also be in a working location for the script to start with.

Michael Homer
  • 76,565
  • Backup files are generated by root. I know it might not be the best practice, but I don't have time to reorganize it all now. Thank you! – borsuk Jul 25 '14 at 11:26