0

I am using .bashrc to execute a python script on system boot:

sudo -u pi python3 /path/to/script.py

and then I add @lxterminal to file /etc/xdg/lxsession/LXDE-pi/autostart to make sure a terminal window is opened on launch.

However, when I use ps aux to check all progresses, I found that there's two script.py processes running in the system, even though I call execute the script only once in .bashrc. Having two of the same script running at the same time is causing me troubles. Any help is appreciated.

AdminBee
  • 21,637
  • 21
  • 47
  • 71
michael
  • 1
  • 1
  • 1
    [What is the purpose of `.bashrc` and how does it work?](https://unix.stackexchange.com/q/129143/108618) – Kamil Maciorowski Sep 20 '20 at 07:56
  • @KamilMaciorowski I'm adding a line to .bashrc so that on system startup it executes a script. – michael Sep 20 '20 at 08:08
  • 3
    In case you missed it: "`.bashrc` runs on every interactive shell launch". This is very different than "on system startup" and can *easily and commonly* run your script more than once. – Kamil Maciorowski Sep 20 '20 at 09:20

1 Answers1

4

You have a few misconceptions here. Any commands in .bashrc are run every time you start a new interactive non-login shell. This means that every time you open a new terminal, they will run again. Every time you run bash, they will run again.

The next issue is that, unless you have configured your sudo to allow passwordless execution, your command won't even run. It will just hang, waiting for a password. Do you even need sudo? Isn't pi your own username? All commands in your .bashrc will run as your user, you don't need to call sudo for them.

Finally, launching a terminal is irrelevant. The command won't be run in that terminal, the terminal will just sit there.

What you want to do is add this command to /etc/crontab and set it to run as the user pi on reboot. Run sudo nano /etc/crontab and add this line to the file:

@reboot pi python3 /path/to/script.py

That will tell your system to run the command python3 /path/to/script.py as the user pi on every reboot.

terdon
  • 234,489
  • 66
  • 447
  • 667