Search code examples
pythonbashraspberry-pi2

run script form .bashrc only once


I want a python script to be executed at bootup on my raspberry pi2, so I put it into .bashrc. Launching the script with crontab didn't work.

But I only want to execute it once. Not everytime I enter a terminal or every time I login via ssh. My poor try of course didn't work and it's obvious why.

python_running=false
if [ "$python_running" = false ] ; then
  ./launcher.sh
  $python_running = true
fi

EDIT: My main problem is that the python script needs internet access. The connection has to be established before the script is executed. After the first answer and comments I realized that .bashrc is not a good place for launching the script at bootup. It works with autologin, but is not a proper solution. But what could be a proper solution to run the script only once?


Solution

  • .bashrc is definetly not a proper place to do that. To start the script at bootup the best and easiest solution I found is crontab:

    sudo crontab -e
    

    then add the following line to the end of the file:

    @reboot sh /home/pi/launcher.sh > /home/pi/logs/cronlog 2>&1
    

    But to use crontab the shell script needs to be changed to wait/poll for internet connection:

    ROUTER_IP=192.168.0.1
    while ( ! ping -c1 $ROUTER_IP) do
      echo "network is not up yet"
      sleep 3
    done
    echo "network is up now"
    python3 myScript.py &
    

    Polling might not be the best option, but there's nothing wrong in creating one sleep process every 3 seconds.