Search code examples
terminalraspberry-piraspberry-pi3startupsudo

Run Terminal at startup and execute command as sudo


I'm trying to run an executable file as sudo using terminal at startup but I'm having some issues. I couldn't find the solution in other answers, so I opened up this one. I'm using a Raspberry Pi 3 B+ with the Raspbian Stretch with desktop and recommended software downloaded from the official Raspberry Pi website.

I have an executable that needs to be run with sudo (I use the pigpio library to communicate with another hardware through SPI and if I don't run the executable with sudo, the pigpio doesn't work). What I'm trying to achieve is that when the Pi finishes to startup the graphical interface, it would run the LXTerminal and execute "sudo home/pi/myfolder/myprogram".

I've tried:

sudo nano ~/.config/autostart/myprogram.desktop

[Desktop Entry]
Encoding=UTF-8
Type=Application
Name=myprogram
Exec=lxterminal -e "sudo /home/pi/myfolder/myprogram"
Terminal=true

sudo chmod a+r ~/.config/autostart/myprogram.desktop

Also tried:

sudo nano /etc/xdg/lxsession/LXDE-pi/autostart

lxterminal --command="sudo /home/pi/myfolder/myprogram"

Both methods did open the lxterminal at startup, but didn't executed my program. Can anyone help me out?


Solution

  • I found the solution, so I'm gonna post it here in case someone else needs it. If it already exists in somewhere else around here, feel free to tag it as duplicated. The solution that worked for me was this:

    sudo nano ~/.config/autostart/myprogram.desktop
    
    [Desktop Entry]
    Encoding=UTF-8
    Type=Application
    Name=myprogram
    Exec=lxterminal -e bash -c 'sudo /home/pi/myfolder/myprogram;$SHELL'
    Terminal=true
    
    sudo chmod a+r ~/.config/autostart/myprogram.desktop
    

    The $SHELL makes the terminal stay open after myprogram ends its execution. If you don't need this feature, just exclude the ;$SHELL part of the code above.