Autoinstall script for systemd service

The following script will install a systemd service file into /etc/systemd/system/ and enable it (i.e. start on boot) and start it immediately.

#!/bin/bash
# This script installs and enables/starts a systemd service
export NAME=MyService

# Create service file
cat >/etc/systemd/system/${NAME}.service <<EOF
# ADD SYSTEMD SERVICE FILE CONTENT HERE
EOF

# Enable and start service
systemctl enable --now ${NAME}

In order to modify the script for your systemd service, replace MyService by the desired name of your service in

export NAME=MyService

and insert the content of your .service file at

# ADD SYSTEMD SERVICE FILE CONTENT HERE

Full example

The following complete example installs a systemd service named MyService that runs /usr/bin/python3 myscript.py:

#!/bin/bash
# This script installs and enables/starts a systemd service
export NAME=MyService

# Create service file
cat >/etc/systemd/system/${NAME}.service <<EOF
[Unit]
Description=MyService

[Service]
Type=oneshot
ExecStart=/usr/bin/python3 myscript.py
WorkingDirectory=/opt/myservice

[Install]
WantedBy=multi-user.target
EOF

# Enable and start service
systemctl enable --now ${NAME}