-
Notifications
You must be signed in to change notification settings - Fork 4
/
eos-sleep-counter
executable file
·62 lines (53 loc) · 1.49 KB
/
eos-sleep-counter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/bin/bash
# After each second, show seconds remaining until this program exists.
#
# The output is displayed on one line.
# Pressing any key will stop this program.
#
# Exit code is
# - 0 if any regular key was pressed
# - 130 if the program was interrupted with Ctrl-C
# - 142 if timeout occurred
#
# Parameters:
# $1 = number of seconds (integer) before the program exists
# $2 = (optional) prompt to show before showing the remaining seconds
printf2() { printf "$@" >&2 ; }
ShowTime() {
CountOfSubtrings() {
# how many "substring"s there are in the given "string"
local string="$1"
local substring="$2"
local length=${#string}
local sublength=${#substring}
string=${string//$substring/}
local newlength=${#string}
return $(( (length - newlength) / sublength ))
}
CountOfSubtrings "$prompt" "%s"
case "$?" in
1) printf2 "\r$prompt\r" "$s" ;;
2) printf2 "\r$prompt\r" "$s" "$seconds" ;;
*) printf2 "unsupported prompt '%s'\n" "$prompt" ;;
esac
}
Main() {
local -r seconds="$1"
local prompt="$2"
local s
local ret=0
local str=""
[ -n "$prompt" ] || prompt="[Close in %s/%s seconds (or press a key to close)]"
for ((s=seconds; s>0; s--)) ; do
ShowTime
read -t1 -n1 str
ret=$?
[ $ret -eq 0 ] && break
done
ShowTime
if [ $ret -ne 0 ] || [ -n "$str" ] ; then
printf2 "\n"
fi
return $ret
}
Main "$@"