Why is using set -e causing my script to crash when called in a crontab?

I have a bash script that does multiple file operations. When any user runs this script, it succeeds and prints out multiple lines of text, but when I try to do this, problems are encountered. It seems to run (I can see a cron log entry showing that it was started), but nothing happens, it does not output anything, and does not perform any file operations. It also doesn't show up in running processes anywhere, so it seems to log out immediately.

After some troubleshooting I found that removing "set -e" solved the problem, now it starts from cron without issue. So this works, but I'd rather set -e, so the script exits if there is an error. Does anyone know why "set -e" is causing my script to exit?

Thanks for the help,
Ryan

+2


a source to share


2 answers


When your script is running under cron, environment variables and path may be set differently than when the script is run directly by the user. Perhaps why is this behaving differently?

To test this: create a new script that does nothing except printenv

and echo $PATH

. Run this script manually, saving the output, and then run it as a cron job, saving that output. Compare the two environments. I'm sure you'll find the differences ... an interactive login shell will create its environment by searching for ".login", ".bash_profile", or a similar script (depending on the user's shell). This usually does not happen in cron, which is usually the reason the cron job behaves differently than the same script does in the login shell.



To fix this: At the top of the script, either the environment and PATH variables are explicitly set according to the interactive environment or user source ".bash_profile", ".login", or another script setting, depending on the shell used.

+4


a source


C set -e

, the script will stop at the first command that gives a non-zero exit status. This does not necessarily mean that you will see an error message.

Here's an example using a command false

that does nothing except exit with an error status.

Without set -e

:

$ cat test.sh
#!/bin/sh

false
echo Hello

$ ./test.sh
Hello
$

      



But the same script with set -e

exits without printing:

$ cat test2.sh
#!/bin/sh

set -e

false
echo Hello

$ ./test2.sh
$ 

      

Based on your observations, it looks like your script isn't working for some reason (presumably related to a different environment as Jim Lewis suggested) before it generates any output.

To debug, add set -x

to the beginning of your script (s set -e

) to show commands as they run.

+4


a source







All Articles