Bash script not executing from crontab [duplicate]
I have the following bash script:
#!/bin/bash
mysqldump -u ******** -p******** --all-databases | gzip > /home/srvlinux01/MySQLBackups/database_$(date +\%Y-\%m-\%d).sql.gz
which is located in /home/srvlinux01/MySQLBackups/
as backup.sh
with the following permissions
-rwxr--r-- 1 root root 134 feb 27 12:48 backup.sh
I've set up a cronjob on sudo crontab -e
to run it every day, at night
#Automatic MySQL backup
30 3 * * * sh /home/srvlinux01/MySQLBackups/backup.sh
But I get emailed the following error:
sh: 0: Can't open /home/srvlinux01/MySQLBackups/backup.sh
I've been trying different setups, but can't figure out what is wrong. I can run the script manually and everything goes perfectly, so I guess there is something wrong with my cronjob entry, but can't really understand what. Could you please help me figure it out? Thanks!
You need to give your cron a PATH
. For instance:
SHELL=/bin/sh PATH=/bin:/sbin:/usr/bin:/usr/sbin
In your case, try putting this before your command. Check the community wiki in this question for more information on why the PATH
variable is needed. Here is an excerpt; essentially the idea is that cron does not read /etc/environment
:
A common "gotcha" is the PATH environment variable being different. Maybe your cron script uses the command
somecommand
found in/opt/someApp/bin
, which you've added toPATH
in/etc/environment
? cron does not read that file, so runningsomecommand
from your script will fail when run with cron, but work when run in a terminal. To get around that, just set your ownPATH
variable at the top of the script.
chmod +x /home/srvlinux01/MySQLBackups/backup.sh
try to run your script with full path on commandline:
/home/srvlinux01/MySQLBackups/backup.sh
if it is not running - there is something wrong (path error)
Make sure this is your crontab
crontab -e
no sudo :
sudo crontab -e
is root crontab - and root is not able to find your script ;)
remove "sh" in crontab just write:
30 3 * * * /home/srvlinux01/MySQLBackups/backup.sh
I can see one mistake in your crontab file configuration. In the below config you are trying to call backup.sh
as same as in your shell prompt with sh
prefix which may not work in cron.
#Automatic MySQL backup
30 3 * * * sh /home/srvlinux01/MySQLBackups/backup.sh
Solution:
- change the owner as said in comment, if needed.
- Make it as executable.
chmod a+x <filename>
-
Update your crontab to reflect this. (calling the file directly, shell is used as per shebang line inside the file)
#Automatic MySQL backup 30 3 * * * /home/srvlinux01/MySQLBackups/backup.sh
I hope this would help.