2009/01/01

Linux: how to run a script on sleep and hibernation

If you want to run a script when your PC is about to enter sleep (standby) or hibernation (suspend) state, your script must be created in /etc/pm/sleep.d, and I mean created, because if you symlink there a script you created somewhere else the script will not get executed.

You can name the script whatever you like but the filename must have "25-" as prefix and the extension should be ".sh". That number in particular is for the script to be executed before any network interface in the PC is shut down, something useful for script performing synchronization tasks between computers. If your script does not need network functionality the prefix could be any number, or have no number at all.

An easy way to test if a script was executed before the PC entered sleep or hibernation states is with this script, which creates an empty file called "hello" in your Home directory:
#!/bin/bash
touch /home/pablo/hello

The hello file will be created by root, but you can delete it anyway.