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

5

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.

4

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.