Maybe a short example for a systemd
service will do.
This is our infinite script, location /path/to/infinite_script
, executable bit set:
#!/bin/bash
while ((1)) ; do
date >> /tmp/infinite_date
sleep 2
done
No we need to define a service file:
[Unit]
#just what it does
Description= infinite date service
[Service]
#not run by root, but by me
User=fiximan
#we assume the full service as active one the script was started
Type=simple
#where to find the executable
ExecStart=/path/to/infinite_script
#what you want: make sure it always is running
Restart=always
[Install]
#which service wants this to run - default.target is just it is loaded by default
WantedBy=default.target
and place it in /etc/systemd/system/infinite_script.service
Now load and start the service (as root):
systemctl enable infinite_script.service
systemctl start infinite_script.service
The service is running now and we can check its status
systemctl status infinite_script.service
● infinite_script.service - infinite date service
Loaded: loaded (/etc/systemd/system/infinite_script.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2019-05-28 14:18:52 CEST; 1min 33s ago
Main PID: 7349 (infinite_script)
Tasks: 2 (limit: 4915)
Memory: 1.5M
CGroup: /system.slice/infinite_script.service
├─7349 /bin/bash /path/to/infinite_script
└─7457 sleep 2
Mai 28 14:18:52 <host> systemd[1]: Started infinite date service.
Now if you kill the script (kill 7349
- main PID) and check the status again:
● infinite_script.service - infinite date service
Loaded: loaded (/etc/systemd/system/infinite_script.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2019-05-28 14:22:21 CEST; 12s ago
Main PID: 7583 (infinite_script)
Tasks: 2 (limit: 4915)
Memory: 1.5M
CGroup: /system.slice/infinite_script.service
├─7583 /bin/bash /path/to/infinite_script
└─7606 sleep 2
Mai 28 14:22:21 <host> systemd[1]: Started infinite date service.
So note how it was just restarted instantly with a new PID.
And check the file ownership of the output:
ls /tmp/infinite/date
-rw-r--r-- 1 fiximan fiximan 300 Mai 28 14:31 infinite_date
So the script is run by the correct user as set in the service file.
Of course you can stop and disable the service:
systemctl stop infinite_script.service
systemctl disable infinite_script.service
EDIT:
A few more details: a user's personal services can (by default) be placed in $HOME/.config/systemd/user/
and managed accordingly with systemctl --user <commands>
. No root needed just like with a personal crontab.