Exit script when shutdown or reboot command is given

This is probably a simple question, but I'm new with writing scripts for Linux (IPFire in this case) and Google wasn't helpful with this.

When creating a script, what is the best and/or proper way to have it exit automatically if the reboot or shutdown command is given? If that's even necessary, I don't know if Linux kills everything that's running by itself or waits like Windows for user input to kill something that was still running.

Anyway, the only thing I could come up with was

While [ "$(runlevel | sed 's/.* //')" = 3 ]

The idea is that the script stays in the while-loop while runlevel is 3, as in normal operation. When the shutdown or reboot command is given, runlevel changes to either 0 or 6, as in not 3, meaning the while-loop will exit. Well, that's the idea anyway.

Does anyone have any thoughts or comments on this?

The OS will terminate the processes, no need to bother.

The OS will terminate the process but if you wanna be clean about this you should handle your application through services management.

  • Start script
  • Stop script
  • Add service

That way when the system boots it will check all the services that need to be started and start your application automaticly. Same thing while your system shuts down it will check all the services to end and will terminate your application cleanly.