bash script not being run by cron
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.
Related videos on Youtube
borsuk
Updated on September 18, 2022Comments
-
borsuk over 1 year
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.
-
Admin almost 10 yearsYour
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. Addcd /correct/path
in the beginning of your script or use an absolute path forfind
. -
borsuk almost 10 yearsI 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 almost 10 yearsBackup 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!