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


当前回答

Cron默认只提供这个环境:

HOME用户的主目录 LOGNAME用户登录名 路径= / usr / bin: / usr / sbin SHELL = / usr / bin / sh

如果需要更多,可以在crontab中的调度表之前定义环境。

其他回答

创建一个cron作业,运行env并将stdout重定向到一个文件。 使用该文件和“env -”一起创建与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.

我不相信有;我所知道的测试cron作业的唯一方法是设置它在未来运行一到两分钟,然后等待。

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

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

你可以运行:

env - your_command arguments

这将在空环境下运行your_command。