In this article, we would cover how to run shell script as systemd service in Ubuntu. systemd service starts with Process ID 1 and rest of the processes follow it. There is something pretty exciting for the regular user with systemd and that is – creating a script which can be invoked at the system boot and keeps running till we shutdown.
Create a shell script
A simple shell script (i.e. firstscript.sh) which creates an empty directory hello/ in /dev/shm –
#!/bin/sh mkdir /dev/shm/hello
mkdir command would create a directory hello in /dev/shm
Now, make the script executable –
chmod u+x firstscript.sh
Next, move the firstscript.sh to /usr/local/bin directory –
sudo mv firstscript.sh /usr/local/bin
Create a systemd startup script
Here, we create a systemd startup script which ends with .service extension. So, open a text editor and save the file as firstscript.service
We have used nano text editor here –
sudo nano /etc/systemd/system/firstscript.service
Append the file with following code –
[Unit] Description=First script [Service] ExecStart=/usr/local/bin/firstscript.sh [Install] WantedBy=multi-user.target
It contains three fields – Unit, Service and Install. Data we have provided in all the three fields in self-explanatory.
Now, we need to reload systemd daemon –
sudo systemctl daemon-reload
Lastly, to check the status of our script –
sudo systemctl status firstscript.service
It would return with –
Loaded: loaded (/etc/systemd/system/firstscript.service; disabled; vendor preset: enabled) Active: inactive (dead)
Enable the systemd service
So, we need to enable it first –
sudo systemctl enable firstscript.service
If we want to start it straight-away then,
sudo systemctl start firstscript.service
You would see hello/ directory in /dev/shm at this stage and at every boot.
We have used a very simple script just to illustrate how things work through systemd. If we want to disable the service then –
sudo systemctl stop firstscript.service sudo systemctl disable firstscript.service
In conclusion, we have covered how to create a shell script and a systemd startup script. Later, we saw how we can enable/disable it as systemd service.