pvas
pvas

Reputation: 73

Bash script runs manually in terminal but is not executed from crontab

I have a bash script that I want to be executed every 15 minutes, so I added this line to my crontab:

7,22,37,52 * * * * /path/to/my/script.sh

I've checked the directory path to be correct and the script runs correctly if I just run /path/to/my/script.sh manually from any directory. I have this bang line in my script:

#!/usr/bin/env bash

My script also references other scripts in the same directory as it, and I have run chmod +x on all scripts that are needed. I set the MAILTO to my email address and I was getting some Cron Daemon emails when I changed the line in my crontab to:

7,22,37,52 * * * * sh /path/to/my/script.sh

But I never received emails upon using

 7,22,37,52 * * * * /path/to/my/script.sh

or

7,22,37,52 * * * * bash /path/to/my/script.sh

I made sure cron is running and I've also tried redirecting the output of my script to a log file, which is also only written in when I include the sh. However, if I run sh /path/to/my/script.sh from the home directory, it does not work. The only ways my script actually runs is if (from any directory) I call /path/to/my/script.sh or bash /path/to/my/script.sh. I'm pretty new to writing bash scripts so any help is very welcome.

Upvotes: 3

Views: 2811

Answers (2)

Xofo
Xofo

Reputation: 1278

@pvas The cron user environment should be treated with extra special care. The assumption that most users have is that they will have access to paths, directories, permissions etc. This is far from the case. Cron runs in a minimal environment and you must set up EVERYTHING - Paths, Permissions and the location where the scripts are running from.

1) I set up the environment myself.

2) I use fully expanded paths in my crontabs.

3) I make sure any directories that need to be read have read permissions.

4) I make sure that my password does not expire because that will block cron when it does.

5) Make sure underlying scripts are explicitly invoked (by Perl, Bash, Python whatever).

6) Pipe the command on the cron line to a LOG file (even better a log file with a TIMESTAMP).

Fix these things and then try again. Cron is particular, you need to set up everything.

For example:

#SETUP ENVIRONMENT
SHELL=/bin/bash
source /home/userfoo/.bash_profile

#RUN THE SCRIPT everyday at 11:50pm (23:50)
50   23  *    *   *  userfoo /home/userfoo/script.sh >> LOGFILE.txt

<<

Upvotes: 3

sjsam
sjsam

Reputation: 21955

Crontab entries should have the following format

m h  dom mon dow   command

which confirms that your entry below

7,22,37,52 * * * * /path/to/my/script.sh

is correct. Having said that, you must close the crontab editor(:wq) for the changes to come to effect.

It is suggested you go through [ this ] cross site post which portrays the possible issues with cron jobs.


More about hashbang [ here ].

Upvotes: 2

Related Questions