Run Script in Non-Interactive Shell – Shell Scripting Tips

cronenvironment-variablesinteractiveshell

I have a cron job that is running a script. When I run the script via an interactive shell (ssh'ed to bash) it works fine. When the script runs by itself via cron it fails.

My guess is that it is using some of the environmental variables set in the interactive shell. I'm going to troubleshoot the script and remove these.

After I make changes, I know I could queue up the script in cron to have it run as it would normally, but is there a way I can run the script from the command line, but tell it to run as it would from cron – i.e. in a non-interactive environment?

Best Answer

The main differences between running a command from cron and running on the command line are:

  • cron is probably using a different shell (generally /bin/sh);
  • cron is definitely running in a small environment (which ones depends on the cron implementation, so check the cron(8) or crontab(5) man page; generally there's just HOME, perhaps SHELL, perhaps LOGNAME, perhaps USER, and a small PATH);
  • cron treats the % character specially (it is turned into a newline);
  • cron jobs run without a terminal or graphical environment.

The following invocation will run the shell snippet pretty much as if it was invoked from cron. I assume the snippet doesn't contain the characters ' or %.

env - HOME="$HOME" USER="$USER" PATH=/usr/bin:/bin /bin/sh -c 'shell snippet' </dev/null >job.log 2>&1

See also executing a sh script from the cron, which might help solve your problem.

Related Question