Skip to content

Instantly share code, notes, and snippets.

@goodarzi
Created January 29, 2024 10:09
Show Gist options
  • Save goodarzi/8de35184397f60e6c2a1491ac3291bb6 to your computer and use it in GitHub Desktop.
Save goodarzi/8de35184397f60e6c2a1491ac3291bb6 to your computer and use it in GitHub Desktop.
Bash script to install it self as systemd timer
#!/usr/bin/env bash
# set -x
script_name=$(basename "${0%.*}")
install_systemd_timer() {
if [ -z "$1" ]; then
echo "Timer interval not defined"
return 1
fi
if [ "$1" -ge 0 ] && [ "$1" -le 60 ]; then
echo "Install systemd timer..."
else
echo "Timer minutes interval is out of range 1 .. 59"
return 1
fi
echo "Install /etc/systemd/system/$script_name.timer"
cat << _EOF_ > /etc/systemd/system/$script_name.timer
[Unit]
Description=$script_name every $1 minutes
[Timer]
OnBootSec=1min
OnCalendar=*:0/$1
[Install]
WantedBy=basic.target
_EOF_
echo "Install /etc/systemd/system/$script_name.service"
cat << _EOF_ > /etc/systemd/system/$script_name.service
[Unit]
Description=$script_name oneshot service
[Service]
Type=oneshot
User=root
Group=root
ExecStart=$(realpath $0)
LogLevelMax=err
# emerg , alert, crit, err, warning, notice, info, debug
_EOF_
systemctl daemon-reload
systemctl enable $script_name.timer
systemctl start $script_name.timer
systemctl status $script_name.timer
}
if [ "$1" = "install" ];then
if install_systemd_timer $2; then
exit 0
else
exit $?
fi
fi
# script to run ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment