How to run a Shell Script before shutdown on CentOS How to run a Shell Script before shutdown on CentOS shell shell

How to run a Shell Script before shutdown on CentOS


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.


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


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

The symlink name should begin with a S - for Start (K for Kill)

The two-digit specifies the order of execution for your script, the lowest numbered being execute first.