4

I am trying to run a simple .sh script on reboot. I would like to have this script running forever. I have this script in a folder in the user directory, in /home/user/folder/script.sh. It runs on a simple vps, and I have access through ssh. If I run it by doing ./script.sh & while I am in the same directory, it works perfectly. When I close the ssh connection, it stops.

I tried to add a crontab entry like this one: @reboot /home/user/folder/script.sh & (as suggested in other answers) and then just type sudo reboot but it doesn't work.

I don't know which one is the best solution to this problem. The script.sh is this one (I found it while searching for some solution to restart the python start.py if it crashes):

until ./start.py; do
    echo "Server 'myserver' crashed with exit code $?.  Respawning.." >&2
    sleep 1
done

And it does exactly what I need.

Thank you for your help!

Michele
  • 553
  • 1
  • 5
  • 16
  • 1
    You should look into process supervisors. There are tools designed to do exactly this job correctly that aren't shell script loop hacks. – Etan Reisner Jul 12 '15 at 17:14
  • 2
    Take a look at this post too -- http://unix.stackexchange.com/questions/109804/crontabs-reboot-only-works-for-root. It mentions several "@reboot" gotchas in the accepted answer. – matthewatabet Jul 12 '15 at 17:19
  • Forget shell scripts and cronjobs, they equally suck at what you are trying to do. Under Linux, init/upstart is the way to make server processes last the uptime of the machine. Look at entries in /etc/init and /etc/init.d for examples. – msw Jul 12 '15 at 18:11
  • Running a cron job in the background makes no sense at all; cron already runs in the background. – tripleee Jul 13 '15 at 03:49

1 Answers1

2

When you close the ssh connection, your script gets a hang-up signal and exits. You can ignore the hang-up signal by using nohup if you start your script like this:

nohup ./script.sh &

Then the script will keep running after you close the connection.

Nathan Wilson
  • 856
  • 5
  • 12