Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a Shell Script before shutdown on CentOS

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.

like image 363
linuxnewbee Avatar asked Dec 07 '22 05:12

linuxnewbee


2 Answers

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.

like image 64
Mahattam Avatar answered Dec 08 '22 19:12

Mahattam


Try to set executable permissions for your script. Sometimes you need to do that to activate it.

chmod 755 /etc/init.d/sendshtmail

Also try to use absolute paths for your command, while quoting the other variable as well.

echo "${SHUTDOWNBODY}" | /usr/bin/mutt -s "${SHUTDOWNSUBJECT}" "${EMAIL}"

Another attempt is to switch your user to your current user e.g.

echo "${SHUTDOWNBODY}" | su -l -c "/usr/bin/mutt -s \"${SHUTDOWNSUBJECT}\" \"${EMAIL}\"" yourusername
like image 29
konsolebox Avatar answered Dec 08 '22 17:12

konsolebox