Autostarting xorg apps
If the script you want to start requires an xorg session then you might try following the freedesktop autostart spec which might or might not work depending on your environment.
Alternatively, you can target your specific desktop environment as described at https://wiki.archlinux.org/index.php/autostarting.
Running a script as a systemd service
If your script fits the description of a daemon or a 'service', and your system is running systemd which is the case for raspbian and most modern linuces, then you can configure your script to run as a systemd service — this provides granular control over the lifecycle and execution environment, as well as preconditions for starting the script, such as the network being up and running. It is also possible to configure the service restart in case of failure (
Restart=always, and delay between restarting e.g.
For system-wide use create your systemd unit file under
/etc/systemd/system, e.g. with
Description=Autossh keepalive daemon
## make sure we only start the service after network is up
## use 'Type=forking' if the service backgrounds itself
## other values are Type=simple (default) and Type=oneshot
## here we can set custom environment variables
ExecStop=/usr/bin/killall -9 autossh
### NOTE: you can have multiple `ExecStop` lines
# don't use 'nobody' if your script needs to access user files
# (if User is not set the service will run as root)
# Useful during debugging; remove it once the service is working
Now we are ready to test the service:
systemctl start autossh
Checking the status of the service:
systemctl status autossh
Stopping the service:
systemctl stop autossh
Once you verified that the service works as expected enable it with:
systemctl enable autossh
NOTE: For security purposes
systemd will run the script in a restricted environment, similar to how
crontab scripts are run, therefore don't make any assumptions about pre-existing system variables. Use the
Environment keys if your script needs specific variables to be defined. Adding
set -x at the top of your bash script and then running
systemctl status my_service might help identify why your script is failing. As a rule of tumb, always use absolute paths for everything including
cat, or explicitly define your $PATH.