【问题标题】:Why doesn't $(which node) work inside a cron job executing a BASH shell?为什么 $(which node) 不能在执行 BASH shell 的 cron 作业中工作?
【发布时间】:2018-08-29 14:36:53
【问题描述】:

根据this answer,cron 无法访问通常与 BASH 终端关联的环境变量的原因是它没有获取用户的 .bashrc 文件。

我有一个脚本可以获取我的 .bashrc 文件,但它仍然无法找到我当前使用的 Node 版本(这意味着我需要列出完整目录并在每次更新时更改它!)。

脚本:

#!/bin/bash

source $HOME/.bashrc # <-- even after sourcing .bashrc, '$(which node)' returns nothing

NODE="$(which node)" # <-- output is blank in cron job
PROCESS="/home/grayedfox/.nvm/versions/node/v8.9.4/bin/node /home/grayedfox/github/blockscrape/main.js"
LOGFILE="/tmp/log.out"

export BLOCKSCRAPECLI="/opt/litecoin-0.14.2/bin/litecoin-cli"

if pgrep -f "$PROCESS" > /dev/null; then
  echo "Blockscrape is doing it's thing - moving on..." >> $LOGFILE
else
  echo "Blockscrape not running! Starting again..." >> $LOGFILE
  echo "Process: $PROCESS" >> $LOGFILE
  echo "Node: $NODE" >> $LOGFILE # <-- outputs only 'Node: ' in log file
  $PROCESS >> $LOGFILE
fi

Crontab:

# make default shell BASH
SHELL=/bin/bash

# reboots litecoin daemon if it dies
@reboot /opt/litecoin-0.14.2/bin/litecoind

# check every minute to see if block scrape running and restart it if not
* * * * * /home/grayedfox/github/blockscrape/restartBlockscrape.sh

我可以确认该节点(并执行“哪个节点”)在我的终端中正常工作。

感谢您的帮助!

【问题讨论】:

  • 您确定您的脚本在 cron 下运行时可以访问 HOME 环境变量吗?
  • 如果您在 ~/.bash_profile(或 ~/.profile)中执行的操作不在 bashrc 中,您可能需要将 bash 作为登录 shell #!/bin/bash -l 运行,尤其是设置你的路径。
  • 你的 .bashrc 中 PATH 的值是多少(如果有的话)?可能是duplicateduplicate
  • 哦哇...这是非交互式运行的 bash 文件。注释掉我的 .bashrc 配置文件中的违规行修复了它。谢谢!

标签: node.js bash cron


【解决方案1】:

正如this answer 中所讨论的 - 这个答案的问题是,在 Ubuntu 16.04(和许多以前的版本)中,如果标准 .bashrc 文件没有以交互方式运行,它就会退出。

从我的 bash 文件中注释掉以下代码已修复它:

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-24
    • 2014-07-23
    • 1970-01-01
    相关资源
    最近更新 更多