Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Nuttapong Punpipat edited this page Nov 17, 2022 · 2 revisions

Sleep Scripting

Many time, that many situations involved things that required to be executed either/both before and after some machine power operation.

Many Surface devices and Linux workarounds also involve that.

To execute command before/after suspending/hibernating/hybrid-sleeping/suspending-then-hibernating, check this sample script:

#!/bin/bash
## REMARK:
# - above shebang is required for scripting file
# - 1st arg passed to executable file is either "pre" (mean that the entry of a power operation) or "post" (mean that the exit of a power operation)
# - 2nd arg passed to executable file is either "suspend", "hibernate", "hybrid-sleep", or "suspend-then-hibernate", depends on what power operation is operating
# - SYSTEMD_SLEEP_ACTION environment variable is helpful for "suspend-then-hibernate", it has value of either  "suspend", "hibernate", or "suspend-after-failed-hibernate"
case $1 in
    pre)
        case $2 in
            hibernate)
                ;;
            hybrid-sleep)
                ;;
            suspend)
                ;;
            suspend-then-hibernate)
                case $SYSTEMD_SLEEP_ACTION in
                    suspend)
                        ;;
                    hibernate)
                        ;;
                    suspend-after-failed-hibernate)
                        ;;
                esac
                ;;
        esac
        ;;
   post)
        case $2 in
            hibernate)
                ;;
            hybrid-sleep)
                ;;
            suspend)
                ;;
            suspend-then-hibernate)
                case $SYSTEMD_SLEEP_ACTION in
                    suspend)
                        ;;
                    hibernate)
                        ;;
                    suspend-after-failed-hibernate)
                        ;;
                esac
                ;;
        esac
        ;;
esac

Save your script in /usr/lib/systemd/system-sleep/, and make it executable by root.

Note that all files inside mentioned directory could be any executable file (either native binary or any scripting file which required shebang).

For more information, see https://www.freedesktop.org/software/systemd/man/systemd-suspend.service.html

Clone this wiki locally