How to run an infinite loop program on startup on a raspberry pi without halting boot up

0

I have a shell script:

#!/bin/bash
while sudo /home/pi/MyCode; do :; done
echo Error with MyCode

which runs a program in an infinite loop. I want to set up the shell script to run at start-up (which I've done with other bash scripts). However, I don't want the script to halt start-up, or prevent me from being to ssh in.

I've seen a lot of people who have had to wipe and remount their SD cards due to infinite loops be created on start-up. How do I prevent this?

I've tried augmenting the code:

#!/bin/bash
while sudo /home/pi/MyCode &; do :; done
echo Error with MyCode

to run MyCode in the background, but I keep getting an error along the lines

unexpected character before ;

Is there a way to run this script on startup without halting my startup? If so, can it be done in a way that I still have the option of SSH'ing and stopping the script at any time?

JRogerC

Posted 2014-09-18T20:16:20.300

Reputation: 101

I'm not sure i understand the question. I don't have a ' before the #!. #!/bin/bash is the fist line of my bash script. – JRogerC – 2014-09-18T21:25:34.417

I made a type. I meant a /, which appears to be gone now anyway. – lzam – 2014-09-18T21:26:40.313

Answers

0

Remove the : It generates the syntax error. Alternatively insert a sleep 1 or something similar instead of it, bash can freak out on empty while ... do loops. If you go with this approach you shoukd also lose the & If you leave it in you will create a new process for every iteration of the loop, grinding your pi to a halt once all your ram is taken.

Also use ./myCode.sh or exec myCode.sh to be shure it actually runs the script.

If you are running raspbian i would also suggest using upstart. This allows for a more controlled way of triggering stuff during boot, like only run once the filesystem is available.

Maybe post the code you want to run also, i can check if there are no other errors. Good for my bash-fu training :-)

Jake

Posted 2014-09-18T20:16:20.300

Reputation: 398

I had this code running for 36 hours straight without error, so I don't think the : is giving me any problems. However, the code is driving an external piece of hardware, and giving it a second of rest would not be a bad thing. – JRogerC – 2014-09-18T21:24:05.423

0

Put the loop in its own script, running in the background:

startup script:

#!/bin/bash
mainloop.sh &
echo Should get here

mainloop.sh:

#!/bin/bash
while sudo /home/pi/MyCode; do :; done

There's probably a way to do this in one script, I'm not familiar enough with Bash to do it though.

baochan

Posted 2014-09-18T20:16:20.300

Reputation: 1 019