Systemd – How to Write a Systemd Script

16.04bootinitsystemd

I have a process that I need to run at startup. It is something that needs to stay running the entire time that the machine is on. As of now I am just typing the following into bash everything I start my server.

command -f argument & disown

I know that I need to make an init script, but I had no idea how. After some research, it seems Ubuntu uses systemd (some references said Upstart, they aren't the same right?) as its init system. But all the guides I found online tell me to place my executable in /etc/init or /etc/init.d. Init is supposed to be a completely different init system.

Can someone please point me in the right direction? A sample systemd script or even an online guide would be a great help.

Best Answer

You need two files:

  1. Your script file:

    command.sh
    
  2. The .service file to be placed in /etc/systemd/system and given permission of 644 with chmod 664 command.service:

    command.service
    
  3. The simplest content of command.service would be:

    [Unit]
    Description=Some service description
    
    [Service]
    ExecStart=/bin/bash -c "/path/to/command.sh -f argument & disown"
    
    [Install]
    WantedBy=multi-user.target
    
  4. Now to make it launch at boot we use the systemd controller systemctl:

    sudo systemctl enable command
    
    # or 
    
    sudo systemctl enable command.service
    

Note many more options are available for the various sections, see here, and make sure your command.sh is executable with chmod +x command.sh

Related Question