How to run a script when suspending/resuming? - Sony VAIO Ubuntu 12.04

Question: How to assign a script to run when selecting the suspend option on the power menu?

Context:
I have a Sony VAIO laptop with an AMD Radeon graphics card. I would like to be able to disable/enable the discrete graphics card. I have no problem in doing this but it causes problems when suspending & resuming from suspend.

When the session is resumed from suspend (with the discrete DPU disabled), the fan will spin up uncontrollably, what I would like to do is edit the suspend script or assign a new script to the suspend option on the power menu. This is so I can re-enable the GPU before suspending. Power Menu

EDIT: After some research I think it has something to do with the files in /etc/pm/sleep.d/?

If I put a custom script in there would it be run when suspending and resuming from suspend?

How do I differentiate in the script between suspending/resuming?


Solution 1:

You are right. You have to write a script and save it to /lib/systemd/system-sleep/ (since 2015 systemd take care of that, before was /etc/pm/sleep.d/). The difference between suspending and resuming is given as a parameter to the script:

#!/bin/bash

case "$1" in
    suspend)
        # executed on suspend
        ;;
    resume) 
        # executed on resume
        ;;
    *)
        ;;
esac

If you also want to do it for hibernate, the arguments would be hibernate and thaw.

Solution 2:

On current Ubuntu versions which use systemd, you can put scripts (or links to scripts) into /lib/systemd/system-sleep/.

Try to put this into /usr/local/bin/test-sleep.sh :

#!/bin/sh

## This file (or a link to it) must be in /lib/systemd/system-sleep/

me=$(basename "$0")

case "$1" in
    pre)
        logger -t "$me" "Suspending: \$1=$1, \$2=$2" ;;
    post)
        logger -t "$me" "Resuming: \$1=$1, \$2=$2" ;;
esac

Then make it executable and put a link to it for systemd:

sudo chmod +x /usr/local/bin/test-sleep.sh
sudo ln -si /usr/local/bin/test-sleep.sh  /lib/systemd/system-sleep/

The script just writes to syslog, so you can see what it did with

grep 'test-sleep' /var/log/syslog