Reputation: 31
I figured I'd ask my first SO question after spending all day breaking my head over this.
So, I have this bash script that fully works when I run it from anywhere and from both my user and root. All it does is move some files around, then execute a python3 script and a mysql statement:
#!/bin/bash
rm -rf /some/directory
cp -r /origin/directory /destination/directory
/usr/bin/python3 /python/script/directory.py
/usr/bin/mysql --login-path=host --database=dbname -e 'CALL function()'
The problem arises when I try to put it into cron. Since these commands require sudo, I added it into the sudo crontab -e
and did some testing. The problem is that the command executes, yet nothing happens.
This is what I put in on the crontab:
0 * * * * bash /directory/with/script.sh 2>&1 > /directory/with/script/latest_run
And this is the output when checking sudo grep CRON /var/log/syslog
:
Jun 8 00:42:01 hostname CRON[7148]: (root) CMD (bash /directory/with/script.sh 2>&1 > /directory/with/script/latest_run)
However, when I check the file latest_run
it returns empty. It does get created every time. And more worrisome is that the database I'm trying to update doesn't get any data at all, yet when I execute it myself manually it does everything I need it to do.
I have spent all day playing with things on my distro to see if I can fix this but I can't find any solutions. If anyone knows what's wrong I'd greatly appreciate some help!
Thanks!
Upvotes: 1
Views: 2048
Reputation: 31
I figured it out!
I saw all over people mentioning that the environment of cron for root is actually very small, but being a bash beginner I was unsure on what this meant.
Turns out cron is unable to execute python3 or mysql without having an environment set previously and specified for it to be able to use them.
Therefore adding HOME=/home/myuser
and SHELL=/bin/bash
(as I use bash instead of sh) did the trick.
In other words the crontab ended up like this:
SHELL=/bin/bash
HOME=/home/myuser
0 * * * * /bin/bash /directory/with/script.sh 2>&1 > /directory/with/script/latest_run
I am aware that security-wise one shouldn't set the root cron to use a personal $HOME variable, but it's fine since only 3 people use this server for the same project anyway.
Thanks everyone!
Upvotes: 2