Crontab and testing a command to be executed

你说的曾经没有我的故事 提交于 2019-12-02 08:48:25
  1. Write a shell script that you can test.
  2. Execute that shell script from the crontab.
  3. Remember that cron provides barely any environment - so your script may have to fix that. In particular, your profile will not be used.
  4. Do not get fancy with what you put in the crontab.
  5. Build a debug mode into your shell script.

No, there isn't specifically a mode that shows errors. Usually, if the cron job witters, the output is emailed to you. That is, it sends standard output and standard error information to you if the executed command writes anything to either standard output or standard error.

On MacOS X (10.6.7), the environment I got was (via a crontab entry like 12 37 17 5 * env >/tmp/cron.env):

SHELL=/bin/sh
USER=jleffler
PATH=/usr/bin:/bin
PWD=/Users/jleffler
SHLVL=1
HOME=/Users/jleffler
LOGNAME=jleffler
_=/usr/bin/env

Of those, PWD, _ and SHLVL are handled by the shell. So, to test your script reliably in a cron-like environment, use:

(cd $HOME
 env -i \
    SHELL=/bin/sh \
    USER=$USER \
    PATH=/usr/bin:/bin \
    HOME=$HOME \
    LOGNAME=$LOGNAME \
    /path/to/script/you/execute ...
)

The -i option to env means 'ignore all inherited enviroment'; the script will see exactly the five values specified plus anything the shell specifies automatically. With no arguments, env reports on the environment; with arguments, it adjusts the environment and executes a command.

To execute a script "manually" you first have to make it executable by doing:

$ chmod +x yourScriptName

Then do either

$ ./yourScriptName

if you execute it from its path or

$ /full/path/to/yourScriptName

from anywhere.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!