How to Run Shell Script as Systemd Service in Redhat - CentOS

Systemd is a software application that provides an array of system components for Linux operating systems. It is responsible for initializing the boot sequence and runs with PID 1, making it an essential component of the system. With systemd, you can easily manage system and application services on your Linux operating system.

You can also run custom scripts as systemd services, allowing them to start during system boot or run continuously. Here’s an example of a systemd service file to start the “ScriptService”:

  1. Open the systemd service directory:

    cd /etc/systemd/system
    
  2. Create a new service file:

    vi ScriptService.service
    

    Modify the values in the file to specify the correct installation directory for ExecStart and ExecStop.

    Here is a sample ScriptService file:

    #
    [Unit]
    Description=Example ScriptService
    After=network.target
    
    [Service]
    ExecStart=/home/user/ScriptService.sh -start
    ExecStop=/home/user/ScriptService.sh -stop
    Type=forking
    
    [Install]
    WantedBy=default.target
    

    Save the file and exit the editor.

To start, stop, or check the status of the ScriptService:

  1. Reload the systemctl daemon to read the new service file:

    sudo systemctl daemon-reload
    
  2. Start the service:

    sudo systemctl start ScriptService
    
  3. Stop the service:

    sudo systemctl stop ScriptService
    

Once you start the ScriptService with the systemctl start ScriptService command, any scripts, databases, or applications configured to autostart will be launched by the ScriptService.

To enable the service to start at boot time:

sudo systemctl enable ScriptService

To create a sample shell script to run continuously until the system is running, follow these steps:

  1. Create a new shell script:

    vi /home/user/ScriptService.sh
    

    Add the following sample script:

    #!/bin/bash
    
    # Check OS Version
    echo "Finding OS Codename..."
    
    CODENAME=$(cat /etc/*-release | grep "VERSION=")
    CODENAME=${CODENAME##*\(}
    CODENAME=${CODENAME%%\)*}
    
    echo "$CODENAME" > /tmp/OS-ver.log  # Create OS log in /tmp/ 
    

    Save the script and set the execute permission:

    sudo chmod +x /home/user/ScriptService.sh
    

Finally, you can verify if the script is running as a systemd service:

sudo systemctl status ScriptService.service

The output should look similar to the following: