Gentoo Linux: Run a script at shutdown, but not when rebooting
September 6, 2015 Leave a comment
In Gentoo Linux it is straightforward to run scripts automatically when the OS starts (boots) and stops (either shutting down or rebooting). You simply need to place an executable script file in the directory
/etc/local.d/ with the suffix ‘
.start‘ or ‘
.stop‘, depending on whether you want the script to run at the beginning or end of your Linux session. The file
/etc/local.d/README (complete with ‘sequentially’ misspelt) explains it better:
This directory should contain programs or scripts which are to be run
when the local service is started or stopped.
If a file in this directory is executable and it has a .start extension,
it will be run when the local service is started. If a file is
executable and it has a .stop extension, it will be run when the local
service is stopped.
All files are processed in lexical order.
Keep in mind that files in this directory are processed sequencially,
and the local service is not considered started or stopped until
everything is processed, so if you have a process which takes a long
time to run, it can delay your boot or shutdown processing.
Scripts with a ‘
.stop‘ suffix are launched both when you shutdown your Linux installation and when you reboot it. However, sometimes you may not want to run a script when you reboot your installation. A typical example would be a script to backup your hard drive; you would probably only want it to run when you have finished for the day and you are shutting down and powering off your machine. So, how do you achieve that? I initially thought I would be able to use the ‘
runlevel‘ command or the
RUNLEVEL environment variable in a script (see
man runlevel regarding both). But I could not get my script
/etc/local.d/10-run_on_shutdown.stop to work using either. However, the command ‘
who -r‘ (‘
who --runlevel‘) does work for me in Gentoo Linux with OpenRC:
After rebooting, then shutting down and booting, then rebooting again, the contents of the file
test.txt show that the above-mentioned simple script works as intended:
So the following script
/etc/local.d/10-run_on_shutdown.stop will do the desired job:
Don’t forget to make the script executable: