我通常有几个问题,如何cron执行脚本,因为他们通常没有我的环境设置。是否有一种方法可以调用bash(?)以同样的方式cron,这样我就可以在安装它们之前测试脚本?


当前回答

回答https://stackoverflow.com/a/2546509/5593430展示了如何获取cron环境并将其用于您的脚本。但是请注意,环境会因所使用的crontab文件而有所不同。我创建了三个不同的cron条目,通过env >日志保存环境。这些是在Amazon Linux 4.4.35-33.55.amzn1.x86_64上的结果。

1. 使用root用户创建全局/etc/crontab

MAILTO=root
SHELL=/bin/bash
USER=root
PATH=/sbin:/bin:/usr/sbin:/usr/bin
PWD=/
LANG=en_US.UTF-8
SHLVL=1
HOME=/
LOGNAME=root
_=/bin/env

2. root用户crontab (crontab -e)

SHELL=/bin/sh
USER=root
PATH=/usr/bin:/bin
PWD=/root
LANG=en_US.UTF-8
SHLVL=1
HOME=/root
LOGNAME=root
_=/usr/bin/env

3./etc/cron.hour /脚本

MAILTO=root
SHELL=/bin/bash
USER=root
PATH=/sbin:/bin:/usr/sbin:/usr/bin
_=/bin/env
PWD=/
LANG=en_US.UTF-8
SHLVL=3
HOME=/
LOGNAME=root

最重要的是PATH, PWD和HOME不同。确保在cron脚本中设置这些以依赖稳定的环境。

其他回答

一些方法:

Export cron env and source it: Add * * * * * env > ~/cronenv to your crontab, let it run once, turn it back off, then run env - `cat ~/cronenv` /bin/sh And you are now inside a sh session which has cron's environment Bring your environment to cron You could skip above exercise and just do a . ~/.profile in front of your cron job, e.g. * * * * * . ~/.profile; your_command Use screen Above two solutions still fail in that they provide an environment connected to a running X session, with access to dbus etc. For example, on Ubuntu, nmcli (Network Manager) will work in above two approaches, but still fail in cron. * * * * * /usr/bin/screen -dm Add above line to cron, let it run once, turn it back off. Connect to your screen session (screen -r). If you are checking the screen session has been created (with ps) be aware that they are sometimes in capitals (e.g. ps | grep SCREEN) Now even nmcli and similar will fail.

取决于shell的账户

sudo su
env -i /bin/sh

or

sudo su
env -i /bin/bash --noprofile --norc

从http://matthew.mceachen.us/blog/howto -模拟- - cron -环境- 1018. - html

将此添加到您的crontab(临时):

* * * * * env > ~/cronenv

运行后,执行以下操作:

env - `cat ~/cronenv` /bin/sh

这假设您的cron运行/bin/sh,不管用户的默认shell是什么,它都是默认的。

脚注:如果env包含更高级的配置,例如PS1=$(__git_ps1 " (%s)")$,它将神秘地错误env: ":没有这样的文件或目录。

在我的例子中,cron正在使用sh执行我的脚本,它不能执行一些bash语法。 在我的脚本中,我添加了env变量SHELL:

#!/bin/bash
SHELL=/bin/bash

你可以运行:

env - your_command arguments

这将在空环境下运行your_command。