Crmgo Blog

Auto-starting a script in CentOS 7 using systemd

Auto-starting a script in CentOS 7 using systemd

Systemd introduces the concept of systemd units. Units are represented by configuration files located in one of the following directories: /usr/lib/systemd/system/ – units from installed RPM packages; /run/systemd/system/ – units created at runtime. This directory takes precedence over the directory containing units installed from packages. /etc/systemd/system/ – units created…

Auto-starting a script in CentOS 7 using systemd

Systemd introduces the concept of systemd units. Units are represented by configuration files located in one of the following directories:

  • /usr/lib/systemd/system/ – units from installed RPM packages.
  • /run/systemd/system/ – units created at runtime. This directory takes precedence over the directory containing units installed from packages.
  • /etc/systemd/system/ – units created and managed by the system administrator. This directory takes precedence over the directory containing units created at runtime.

 

 

Create our service file:

# touch /etc/systemd/system/routing-settings.service # chmod 664 /etc/systemd/system/routing-settings.service

with the following content:

[Unit] Description=Routing Settings Service After=network.target

[Service]
Type=oneshot
User=root
ExecStart=/root/routing.sh

[Install]
WantedBy=multi-user.target

User=root – runs as root! Specify (or do not specify) the user under which your script should run. My script must run as root. I cannot say that I am happy about this, as it requires strict control over the script's location and its access permissions.

Type=oneshot means that the process will complete before further units are started. This is quite suitable for scripts.

Check it:

# systemctl start routing-settings

If, after executing the script, we see the expected result, then enable this "service" for autostart:

# systemctl enable routing-settings

Try rebooting. It should work.

Let's see when our service was started:

# systemctl status routing-settings

Note: This post may be AI-assisted and then human-edited. Editorial responsibility: Dmytro Lomaka, Kaltenkirchen.