Running A Command Before Suspend
To run a script before suspend, place any bash script file in the /usr/lib/systemd/system-sleep/
directory. The scripts themselves can do anything, but there is a certain syntax that must be adhered to. Start by opening up a terminal window. Using sudo -s
, gain a root shell.
Next, up the nano text editor inside the system-sleep directory:
nano /usr/lib/systemd/system-sleep/pre-suspend.sh
Add the shebang to the start of the script. Adding this is critical, and without it, the interpreter will not be able to correctly read the code and commands.
#!/bin/bash/
The next part of the script is the if
. This will tell the power control system that if
the system is about to go down for suspend, something should happen. Paste the code below:
if [ "${1}" == "pre" ]; then sh /path/to/script/to/run.sh
Change sh /path/to/script/to/run.sh
in the script to whatever you’d like to run on your Linux PC (or server) right before the system goes down for suspend. Keep in mind that the line directly after if
does not need to be sh /path/to/script/to/run.sh
. You can also use this to execute various commands. As long as bash can recognize it as a command, it will run.
The last part of the “before suspend” script is to add the “else if” portion. This aspect of the script doesn’t need to be modified, as, in this example, we’re worried about doing something before the system goes down, and not when it wakes back up.
elif [ "${1}" == "post" ]; then # nothing goes here fi
When everything has been added to the file, press Ctrl+O to save nano.
Running A Command After Resume
Executing a command after resume works much like running something before suspend. The only real difference is instead of adding a command after the if
portion of the script, you’d make the most important part of the code occur after the elif
line.
To make a post-resume script, first, add the shebang as the first line.
#!bin/bash
On the next line, add the if
portion of the script.
if [ "${1}" == "pre" ]; then # nothing goes here
With that bit of code pasted into the bash script, move down and paste the “else if” section.
elif [ "${1}" == "post" ]; then sh /path/to/script/to/run.sh fi
Once again, it’s OK to write anything under the elif
line. As long as it is a normal command operation systemd and bash will run it.