You can use this script to create and manage a systemd-based service to automate running a bash script based on systemd timers.
# Project tree
/ automating-bash-script
|__ create-service.sh (create and start systemd-based service)
|__ delete-service.sh (stop and delete systemd-based service)
|__ memchecker.service.stub (systemd-based service stub)
|__ memchecker.timer (systemd-based timer)
|__ memory-checker.sh (the example bash script to be automated)
The memory-checker.sh
reads memory status from /proc/meminfo
, calculates the allocated memory and if
the allocated memory exceeded mem_exceed_limit
value in /etc/default/memchecker
env file, it logs a message to /var/log/memchecker/usage.log
The below variable means that the memory-checker.sh
will log any memory usage above 50% To the /var/log/memchecker/usage.log
You can totaly change this to any number between 1
and 100
mem_exceed_limit=50 # 50%
See, quite uncomplicated example for a bash script!
The create-service.sh
tries to :
- add a new user named
sysbot
- create a memchecker.service and memchecker.timer inside
/lib/systemd/system
- create env file for
memory-checker.sh
in/etc/default/memchecker
- reload systemctl daemon
- enable and start
memchecker.service
andmemchecker.timer
# to create and run the service
./create-service.sh
systemctl status memchecker.service
sudo tail /var/log/memchecker/usage.log
Well everything comes to an end !
You can use the delete-service.sh
to stop and delete everything done back in create-service.sh
.
The delete-service.sh
tries to :
- delete the user
sysbot
- stop and disbale memchecker.service and memchecker.timer
- remove memchecker.service and memchecker.timer from
/lib/systemd/system
- reload systemctl daemon
# to stop and delete the service
./delete-service.sh