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 which desktop environment you are using.
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 (re)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. RestartSec=10
).
For system-wide use create your systemd unit file under /etc/systemd/system
, e.g. with vim /etc/systemd/system/autossh.service
:
[Unit]
Description=Autossh keepalive daemon
## make sure we only start the service after network is up
Wants=network-online.target
After=network.target
[Service]
## use 'Type=forking' if the service backgrounds itself
## other values are Type=simple (default) and Type=oneshot
Type=forking
## here we can set custom environment variables
Environment=AUTOSSH_GATETIME=0
Environment=AUTOSSH_PORT=0
ExecStart=/usr/local/bin/ssh-keep-alive.sh
ExecStop=/usr/bin/killall -9 autossh
### NOTE: you can have multiple `ExecStop` lines
ExecStop=/usr/bin/killall ssh
# don't use 'nobody' if your script needs to access user files
# (if User is not set the service will run as root)
#User=nobody
# Useful during debugging; remove it once the service is working
StandardOutput=console
[Install]
WantedBy=multi-user.target
See also:
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 echo
and cat
, or explicitly define your $PATH.
.xinitrc
or.xsession
file.