【发布时间】: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运行,尤其是设置你的路径。 -
哦哇...这是非交互式运行的 bash 文件。注释掉我的 .bashrc 配置文件中的违规行修复了它。谢谢!