I would like to set up a cron job using crontab -e
.
This job needs to be executed as root, so I thought that simply add an entry in sudo crontab -e
would have been enough. Unfortunately, it isn't.
The script I need to execute works well if I directly type:
sudo /home/user/./script.sh
I am logged in the machine as the user user
, and my crontab entry (sudo crontab -e
) is like the following:
*/1 * * * * /home/user/./script.sh
So, what do I miss here? I have the feeling that the issue is related to the right of the current user or something like this.
First, I was able to get rid of the need to be root to execute the script. My crontab
entry (a classic crontab -e
since I do not need to be root anymore) runs every minute and is:
* * * * * /home/user/script.sh
My script.sh
:
#!/bin/bash
set -e
# Other stuff
Again, it works when a manually type ./script.sh
, but not from the cron job created.
I know have the proof that the script is executed by the cron job. I redirected the error on a file as advised in the comment and get the following error in it:
python: can't open file 'get-status.py': [Errno 2] No such file or directory
To explain this, at one point in my script.sh
, I use docker to execute some other script:
docker run -v $PWD:/t -w /t [image] [command] get-status.py
which again, works manually (./script.sh
) but not from the cron job.
So, I found the issue:
docker run -v $PWD:/t [...]
copy the content of the current directory into the docker container. Since it is executed from cron job, the current directory is of course not the good one, thus the file not found
exception.
I find it quite ugly to do something like docker run -v /home/user/:/t [...]
would there be any other way?
Though this question is marked as a duplicate, it is not the same issue.
I have a PATH
issue within my script, and had to modify it since it is triggered by a cron job which took the $PWD
path of the script.
See my own answer.
./
part in the path to the script. You may need to edit your question to contain the actual script, as there are often problems with scripts run in cron not having the same environment as a script launched form the command line. – Arronical Sep 21 '16 at 12:45ls - l /home/user/script.sh
; ii) change your cron line to* * * * * /home/user/script.sh 2>/tmp/log
and then check the contents of/tmp/log
. Was the file created? Does it contain errors? iii) What is the*/1
supposed to do? If you want to run it every minute, all you need is*
. – terdon♦ Sep 21 '16 at 12:48crontab -e
: See here – jarno Sep 21 '16 at 18:55