0

How can I run a ruby script (rbenv) in bash script for crontab?

I tried:

#!/bin/bash
process=ruby
if ps ax | grep -v grep | grep $process > /dev/null
then
    exit
else
    ruby /home/jason/ruby/project.rb &
fi

exit
enter code here

It works if I run the script as:

./{nameofscript}.sh

but it does not work when I put it on crontab. My crontab setting is like this:

*/2 * * * * root sh /home/jason/ruby/run.sh
sawa
  • 165,429
  • 45
  • 277
  • 381
  • 1
    Possible duplicate of [ruby script using rbenv in cron](https://stackoverflow.com/questions/8434922/ruby-script-using-rbenv-in-cron) – anothermh Oct 19 '18 at 04:49
  • where is the name of the file of my ruby script? – JASON ALBERT SOEGIHARTO Oct 19 '18 at 08:35
  • @JASONALBERTSOEGIHARTO Think anothermh mean that already exist similar answered question. Answer next: */2 * * * * root /home/jason/ruby/run.sh and check is your script has enough rights for execution: chmod +x you_script_name – Ivan Gurzhiy Oct 19 '18 at 09:04

2 Answers2

1

rbenv is not loaded under cron execution session.

You can try to add them dynamically on your $PATH like this:

#!/bin/bash

PATH=$HOME/.rbenv/bin:$HOME/.rbenv/shims:$PATH
process=ruby
if ps ax | grep -v grep | grep $process > /dev/null
then
    exit
else
    ruby /home/jason/ruby/project.rb &
fi
exit
mdegis
  • 2,078
  • 2
  • 21
  • 39
0

1/ you should need to specify sh in your crontab (replace sh /home/jason/ruby/run.sh by /home/jason/ruby/run.sh)

2/ in any case, you may consider using nohup instruction in front of the following instruction, to ensure it won't be hang up during execution

nohup ruby /home/jason/ruby/project.rb &
Bsquare ℬℬ
  • 4,423
  • 11
  • 24
  • 44