1

Is there some variable in Ubuntu (14.04) that could be read in bash script to know in which mode the computer is (active/sleep/suspend)? If yes, is it possible to see also for how long is it current mode.

I would like to make a script that would run when the computer enters in sleep mode.

Same question for variable that would tell in which state the monitor is.

2 Answers2

4

There exists /etc/pm/sleep.d folder which is frequently used for running scripts upon suspend/resume.

The typical form is this:

#!/bin/bash

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

I would suggest you set for suspend option writing the time of suspend to a file (the date command , easiest probably will be date +%s to get the Unix epoch time ) and the same idea for resume, except you will be reading form file into a variable and calculating difference with current time.

Something like this:

#!/bin/bash

case "$1" in
    suspend)
        # executed on suspend
        date +%s > /tmp/suspend_time.txt
        ;;
    resume) 
        # executed on resume
        suspend_time=$(< /tmp/suspend_time.txt)
        current_time=$(date +%s)
        difference=$(($current_time-$suspend_time))
        if [ $difference -gt 60  ]; # greater than 1 minute (60 seconds)
        then
             # put some kind of command you want to run here
        fi
        ;;
    *)
        ;;
esac

Note this is just a draft, and untested, but it's a probable suggestion one could follow.

Sergiy Kolodyazhnyy
  • 105,154
  • 20
  • 279
  • 497
  • For this to work in my system I had do make the target script executable. The available cases suspend, resume, etc are documented in man pm-hibernate – builder-7000 Apr 23 '20 at 21:43
  • Note in the year 2020 someone tried the script and it would not work. This question has an updated answer to above: https://askubuntu.com/questions/1301651/creating-script-to-report-system-suspend-or-awake-is-not-running – WinEunuuchs2Unix Dec 20 '20 at 21:43
3

This is not possible. If your computer is in sleep or suspend mode your program is frozen and can't run any code. If your program is running your computer is active.

  • I was thinking to put the script in /etc/pm/sleep.d and then to have sleep 30 command at the beginning of script and then to control if the mode has changed to active again. If changed -> stop the script. If not -> go on. – NonStandardModel Apr 14 '16 at 10:00
  • The system would enter sleep/suspend only after your script in /etc/pm/sleep.d has finished. – Florian Diesch Apr 14 '16 at 10:18
  • Aha...I understand...but anyway, good enaugh for me. I just wanted to disturb the user as little as possible. Thanks for clarification! – NonStandardModel Apr 14 '16 at 10:28
  • What about at and cron? don't they work even when the computer is suspended? – Sapphire_Brick Jul 26 '20 at 18:55