0

According to this answer the reason cron doesn't have access to environment variables normally associated with a BASH terminal is because it doesn't source the users .bashrc file.

I have a script which does source my .bashrc file but it still fails to find my currently in use version of Node (meaning I need to list the full directory and change it with every update!).

Script:

#!/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

I can confirm that node (and doing "which node") works fine in my terminal.

Thanks for the help!

GrayedFox
  • 2,350
  • 26
  • 44
  • Are you sure that your script has access to the HOME env variable when run under cron? – mikea Mar 20 '18 at 17:16
  • 1
    You may need to run bash as a login shell `#!/bin/bash -l` if there is stuff you do in your ~/.bash_profile (or ~/.profile) that is not in the bashrc, particularly setting up your PATH. – glenn jackman Mar 20 '18 at 19:13
  • 1
    What's the value of PATH in your .bashrc (if any)?. Probably a [duplicate](https://stackoverflow.com/questions/15557777/cron-job-does-not-get-the-environment-variables-set-in-bashrc) or a [duplicate](https://stackoverflow.com/questions/2388087/how-to-get-cron-to-call-in-the-correct-paths). – LMC Mar 20 '18 at 22:00
  • Oh wow... it was the bash file being run non interactively. Commenting out the offending line in my .bashrc profile fixed it. Thank you! – GrayedFox Mar 21 '18 at 06:51

1 Answers1

0

As discussed in this answer - thethis answer problem was that in Ubuntu 16.04 (and many prior versions) the standard .bashrc file quits if it's not being run interactively.

Commenting out the below code from my bash file fixed it:

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac
GrayedFox
  • 2,350
  • 26
  • 44