How to run a Shell Script before shutdown on CentOS

linuxnewbee picture linuxnewbee · Sep 19, 2013 · Viewed 23.7k times · Source

I want to send an email when the system is going to shutdown to an email ID. I have CentOS 6.4. Below is my Script.

cat /ect/init.d/sendshtmail

#!/bin/bash

EMAIL="[email protected]"
SHUTDOWNSUBJECT="["`hostname`"] - System Shutdown"


SHUTDOWNBODY="This is an automated message to notify you that "`hostname`" is shutting down.

LOCKFILE=/var/lock/subsys/SystemEmail
echo "${SHUTDOWNBODY}" | mutt -s "${SHUTDOWNSUBJECT}" ${EMAIL}

It has the appropriate permission. While running it manually it's working perfectly. I have just symlinked it to /etc/rc0.d/ folder. By issuing below command.

 ln -s /etc/init.d/sendshtmail /etc/rc0.d/K00sendshtmail

But the script is not sending any email during shutdown. Thanks in Advance.

Answer

Mahattam picture Mahattam · Mar 20, 2014

Place your shell script in /etc/init.d with executable permission and symlink name should start with K##. If you want to execute your script at first place immediately after shut down then name it with K00scriptname. Script started will K will be executed first based on ascending order then script with S.

ln -s /etc/init.d/script /etc/rc0.d/K00scriptname

Shutdown command will send the stop signal to script, your script (K00scriptname) should have stop function like example

stop()
{
  echo "executing scriptname"
  "Your script logic"
}
case "$1" in
  stop)
    stop
    ;;
esac

Most important, K00scriptname will execute only if there would be lock file present in /var/lock/subsys folder, so do "touch /var/lock/subsys/scriptname" then check by doing shutdown.