script to run when shutdown/reboot

Latest response

I have been working on this for a couple of day on my RHEL test server.

When a shutdown is initiated i want a service to write to a file.

The bash script
/usr/local/scripts/stop_alert.sh

!/usr/bin/env bash

FILEDATETIME=date +%Y%m%d_%H%M

Log configuration

LOG=/var/log/admins/test.log
echo "shutdown server ${FILEDATETIME}" > $LOG

END

I make it exe

chmod +x /usr/local/scripts/stop_alert.sh

I can run it and it adds the test to the $log

So I know the script works.
Then i remove that log file.

I then create a service stop_alert.service

#

[Unit]
Description=Pre-Shutdown TEST
DefaultDependencies=no
Before=shutdown.target reboot.target halt.target

[Service]
Type=oneshot
ExecStop=/bin/bash /usr/local/scripts/stop_alert.sh
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

#

I then did a # systemctl daemon-reload

systemctl enable stop_alert.service

I check and i see the link has been created

ls -al multi-user.target.wants/stop_alert.service

lrwxrwxrwx. 1 root root 38 Sep 15 10:09 multi-user.target.wants/stop_alert.service -> /etc/systemd/system/stop_alert.service

systemctl status stop_alert.service

● stop_alert.service - Pre-Shutdown TEST
Loaded: loaded (/etc/systemd/system/stop_alert.service; enabled; vendor preset: disabled)
Active: active (exited) since Thu 2022-09-15 11:43:16 AEST; 10s ago
Process: 11018 ExecStop=/bin/bash /usr/local/scripts/stop_alert.sh (code=exited, status=0/SUCCESS)

Sep 15 11:43:16 vdevrhelbuild01 systemd[1]: stop_alert.service: Succeeded.
Sep 15 11:43:16 vdevrhelbuild01 systemd[1]: Stopped Pre-Shutdown TEST.
Sep 15 11:43:16 vdevrhelbuild01 systemd[1]: Started Pre-Shutdown TEST.

Then I do a shutdown

When the server comes up and I cat
cat /var/log/admins/test.log

The file is not there.
I do a

cat messages | grep "stop_alert"

It is not there when the server is shutting down.

I do another status

systemctl status stop_alert.service

● stop_alert.service - Pre-Shutdown TEST
Loaded: loaded (/etc/systemd/system/stop_alert.service; enabled; vendor preset: disabled)
Active: active (exited) since Thu 2022-09-15 11:52:33 AEST; 7min ago
Tasks: 0 (limit: 10939)
Memory: 0B
CGroup: /system.slice/stop_alert.service

What am i doing wrong ?

Responses