Aquarius Power的答案似乎效果很好。这是我可能会对他的解决方案做的一些补充。
仅查询锁定状态
如果您只需要单线查询锁定状态,则锁定时应评估为true,如果解锁则应评估为false。
isLocked=$(gdbus call -e -d com.canonical.Unity -o /com/canonical/Unity/Session -m com.canonical.Unity.Session.IsLocked | grep -ioP "(true)|(false)")
查询锁状态和自上次状态更改以来的跟踪时间
现在,如果您需要跟踪屏幕被锁定的时间,则可以采取其他方法。
#!/bin/bash
# To implement this, you can put this at the top of a bash script or you can run
# it the subshell in a separate process and pull the functions into other scripts.
# We need a file to keep track of variable inside subshell the file will contain
# two elements, the state and timestamp of time changed, separated by a tab.
# A timestamp of 0 indicates that the state has not changed since we started
# polling for changes and therefore, the time lapsed in the current state is
# unknown.
vars="/tmp/lock-state"
# start watching the screen lock state
(
# set the initial value for lock state
[ "$(gdbus call -e -d com.canonical.Unity -o /com/canonical/Unity/Session -m com.canonical.Unity.Session.IsLocked | grep -ioP "(true)|(false)")" == "true" ] && state="locked" || state="unlocked"
printf "%s\t%d" $state 0 > "$vars"
# start watching changes in state
gdbus monitor -e -d com.canonical.Unity -o /com/canonical/Unity/Session | while read line
do
state=$(grep -ioP "((un)?locked)" <<< "$line")
# If the line read denotes a change in state, save it to a file with timestamp for access outside this subshell
[ "$state" != "" ] && printf "%s\t%d" ${state,,} $(date +%s)> "$vars"
done
) & # don't wait for this subshell to finish
# Get the current state from the vars exported in the subshell
function getState {
echo $(cut -f1 "$vars")
}
# Get the time in seconds that has passed since the state last changed
function getSecondsElapsed {
if [ $(cut -f2 "$vars") -ne 0 ]; then
echo $(($(date +%s)-$(cut -f2 "$vars")))
else
echo "unknown"
fi
}
本质上,此脚本监视屏幕锁定状态的变化。发生更改时,时间和状态将转储到文件中。如果愿意,可以手动读取此文件,也可以使用我编写的功能。
如果要时间戳而不是秒数,请尝试:
date -ud @$(getSecondsElapsed) | grep -oP "(\d{2}:){2}\d{2}"
不要忘记-u
强迫日期程序忽略时区的开关。