Where to put script to be executed before shutdown ?

Hello,

My AIM is to run my script every time when someone shutdown or reboot my RHEL7 AWS instance.

Query ) Where should i put my script .So, that it gets automatically executed when a server is going down or reboot ?

You would be looking to create the equivalent of a service. If you look in /etc/init.d you will see the scripts used for controlling them and you can create yours here. Make sure it is extremely robust or you may have trouble with the shutdown, or worse problems on boot. Use an existing script to get the skeleton of the script correct.

To get it to run, first determine what is your usual run-level with who -r

Then, using the number returned (usually 2, 3 or 5) link to your script from /etc/rc.d/rc.n.d as a script named with a leading K This will cause it to be run when you leave the run level, i.e. to shut down or reboot.

It is not a process to be done lightly, so be careful. If you get it right, you can run it with service yourname stop to test it. It should be written to ignore or at least recognise service yourname start You could even do similar or varied things with it on system startup. Base it on a known good script that is relatively simple, such as the ntpd service script.

Let us know how you are getting on and if we can help more.

Robin
(half expecting to be castigated/castrated because there is an official way to create a script like this :o)

Oh, hang on, RHEL 7? That means it's systemctl based, so the above may not apply.

I feel a fool :o

Write a service file and place it in /etc/systemd/system/beforeshuttingdown.service

[Unit]
Description=Before Shutting Down

[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/true
ExecStop=<path to script or program>

[Install]
WantedBy=multi-user.target

Your program or script must be executable.

systemctl daemon-reload
systemctl enable beforeshuttingdown.service
systemctl start beforeshuttingdown.service