Jawaban Aquarius Power tampaknya bekerja cukup baik. Inilah beberapa tambahan yang mungkin saya buat untuk solusinya.
Hanya status kunci kueri
Jika Anda hanya perlu satu-liner untuk menanyakan status kunci, ini harus dinilai benar jika dikunci dan salah jika dibuka.
isLocked=$(gdbus call -e -d com.canonical.Unity -o /com/canonical/Unity/Session -m com.canonical.Unity.Session.IsLocked | grep -ioP "(true)|(false)")
Meminta status kunci dan melacak waktu sejak perubahan terakhir dalam status
Sekarang jika Anda perlu melacak berapa lama layar terkunci, Anda mungkin ingin mengambil pendekatan yang berbeda.
#!/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
}
Pada dasarnya, skrip ini mengawasi perubahan dalam kondisi kunci layar. Ketika perubahan terjadi, waktu dan status dibuang ke file. Anda dapat membaca file ini secara manual jika Anda suka atau menggunakan fungsi yang saya tulis.
Jika Anda menginginkan cap waktu alih-alih jumlah detik, coba:
date -ud @$(getSecondsElapsed) | grep -oP "(\d{2}:){2}\d{2}"
Jangan lupa -u
sakelar yang memaksa program tanggal untuk mengabaikan zona waktu Anda.