我通常有几个问题,如何cron执行脚本,因为他们通常没有我的环境设置。是否有一种方法可以调用bash(?)以同样的方式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
默认情况下,cron使用您系统中的sh来执行它的作业。这可能是实际的Bourne shell或破折号,ash, ksh或bash(或另一个)符号链接到sh(并因此在POSIX模式下运行)。
最好的方法是确保您的脚本拥有它们需要的东西,并假设没有为它们提供任何东西。因此,您应该使用完整的目录规范并自己设置环境变量(如$PATH)。
我发现的另一种简单方法(但可能容易出错,我仍在测试中)是在命令之前获取用户的配置文件。
编辑/etc/cron.d /脚本:
* * * * * user1 comand-that-needs-env-vars
会变成:
* * * * * user1 source ~/.bash_profile; source ~/.bashrc; comand-that-needs-env-vars
很脏,但它帮我完成了任务。是否有方法模拟登录?只是一个你可以运行的命令?Bash—登录不起作用。听起来这是更好的方法。
编辑:这似乎是一个可靠的解决方案:http://www.epicserve.com/blog/2012/feb/7/my-notes-cron-directory-etccrond-ubuntu-1110/
* * * * * root su --session-command="comand-that-needs-env-vars" user1 -l
一些方法:
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.
创建一个cron作业,运行env并将stdout重定向到一个文件。 使用该文件和“env -”一起创建与cron作业相同的环境。