从cronjob运行bash脚本无法正常工作

时间:2017-08-17 19:35:53

标签: python bash shell cron anaconda

我正在尝试运行以下bash脚本,该脚本在激活conda环境后运行Python程序。

send.bash

#!/bin/bash
source activate manage_oam_users
python ~/path/to/script/send.py
source deactivate

的crontab

30 * * * * source /path/to/script/send.bash

我从cron得到以下错误,尽管运行source send.bash完美无缺。我也尝试使用bash send.bash,它在手动运行时工作正常,但从cron运行时会导致相同的错误。

/path/to/script/send.bash: line 2: activate: No such file or directory

3 个答案:

答案 0 :(得分:2)

activatedeactivate可能是位于$PATH变量中的条目所指向的脚本。通常,为一个用户本地安装的软件会在.profile文件或.bashrc中添加扩展$PATH变量的语句,以便您可以在不使用完整路径的情况下使用该软件的脚本。

当您的bash自动加载.profile.bashrc时,CRON不会这样做。至少有两个解决方案

A)到处都是完整路径

您可以在CRON作业执行的脚本中使用完整路径,如下所示:

#!/bin/bash
source /path/to/activate manage_oam_users
python $HOME/path/to/script/send.py
source /path/to/deactivate

同时使用$HOME代替~。您可以在shell中使用which activatewhich deactivate找到完整路径。

B)来源.profile.bashrc

或者,您可以在CRON标签中找到.profile(或.bashrc;您必须查看哪个文件扩展了$PATH变量和anaconda目录):

30 * * * * source $HOME/.profile; source /path/to/script/send.bash

额外: source 是什么意思?

  

source 是一个Unix命令,它根据命令评估文件,作为在当前上下文中执行的命令列表。

- from Wikipedia, the something something great encyclopaedia

source命令常用的别名是一个点(. /path/to/script)。

A related, but more generic question can be found on the UNIX and Linux Stack Exchange.

答案 1 :(得分:1)

由于cron没有从安装anaconda的目录运行,因此无法找到激活。你的路径似乎也缺少根anaconda目录。 找到activate命令的位置并将其添加到PATH。

which activate
/Users/username/anaconda/bin/activate

在你的bash_profile中添加

export PATH="/Users/username/anaconda/bin:$PATH"

答案 2 :(得分:0)

此外,可以将目录定义为自动添加

script_dir=$(dirname $0)

#file_imports
source $script_dir"/functions.sh"