services systemd (unit)

Chester Wyke September 23, 2023 Updated: April 15, 2025 #debian

Source: linuxhandbook

Sending output to a file

Source: https://unix.stackexchange.com/questions/245037/saving-process-output-to-a-file-in-systemd-unit-file

Commands are not subject to shell parsing eg “< > << >> and &” are not treated specially. Use /bin/sh 'script.sh > out' to get around this.

File location

If running as root user

File should be saved at etc/systemd/system/

sudo nano /etc/systemd/system/SERVICE_NAME.service

If running as non-root user

File should be saved at ~/.config/systemd/user/ . Note that This folder usually won’t exist so create it.

mkdir -p ~/.config/systemd/user
nano ~/.config/systemd/user/SERVICE_NAME.service

Example Contents

[Unit]
Description=User Facing name of service
After=network.target

[Service]
ExecStart=/bin/bash -c '/usr/bin/my_awesome_program >> /home/user/out.txt 2>&1'
Environment="VAR1=word1 word2" VAR2=word3 "VAR3=$word 5 6"
Type=simple
Restart=always

[Install]
WantedBy=default.target

Enabling and starting the service

If running as root user

sudo systemctl daemon-reload
sudo systemctl enable SERVICE_NAME.service
sudo systemctl start SERVICE_NAME

If running as non-root user

systemctl --user daemon-reload
systemctl --user enable SERVICE_NAME.service
systemctl --user start SERVICE_NAME

Updates to service config

This section applies if you’ve made changes to the service’s configuration and want to apply those changes

If running as root user

sudo systemctl daemon-reload
sudo systemctl restart SERVICE_NAME

If running as non-root user

systemctl --user daemon-reload
systemctl --user restart SERVICE_NAME

Removing Services

Source: https://www.baeldung.com/linux/create-remove-systemd-services#1-removing-custom-systemd-services

If running as root user

sudo systemctl stop SERVICE_NAME
sudo systemctl disable SERVICE_NAME
sudo rm /etc/systemd/system/SERVICE_NAME.service
sudo systemctl daemon-reload

If running as non-root user

systemctl --user stop SERVICE_NAME
systemctl --user disable SERVICE_NAME
rm ~/.config/systemd/user/SERVICE_NAME.service
systemctl --user daemon-reload