Thanks to Jos and the answer by Tracy here: Correct way to execute a script on resume from suspend I got part way. Then I found https://bbs.archlinux.org/viewtopic.php?id=246264.
Full solution: First make a note of your user name (say sam
) and your user id:
id -u sam
Suppose your user id is 1000
. On Ubuntu 22.04 LTS, place a file with this content into /lib/systemd/system-sleep/
(using your user name sam
and id 1000
):
#!/bin/sh
PATH=/sbin:/usr/sbin:/bin:/usr/bin
case "$1" in
pre)
#code execution BEFORE sleeping/hibernating/suspending
/usr/bin/sudo -u sam bash -c "export XDG_RUNTIME_DIR=/run/user/1000; /usr/bin/ogg123 -q /usr/share/sounds/Yaru/stereo/desktop-logoff.oga"
/usr/bin/date >> SOMEDIR/logs/sleep-monitor/pre.log
;;
post)
#code execution AFTER resuming
# same code as above would work here.
;;
esac
exit 0
Check:
- Log and playback should work is called manually (
sudo script.sh pre
).
- The script should work when the system suspends, in that the log file
pre.log
is updated as expected. If that doesn't happen, check about the suspend service (see links above):
sudo systemctl status sleep.target suspend.target hibernate.target hybrid-sleep.target
Final note: Depending on your setup etc etc, it might take a bit for the laptop to actually suspend. So you'll only hear the sound once the laptop lid has been shut for a while.
/lib/systemd/system-sleep/
. – Jos May 09 '22 at 09:47