aboutsummaryrefslogtreecommitdiffhomepage
path: root/bin/unix/timer.sh
diff options
context:
space:
mode:
authorHsieh Chin Fan <pham@topo.tw>2023-02-27 16:04:51 +0800
committerHsieh Chin Fan <pham@topo.tw>2023-02-27 16:04:51 +0800
commitc4377f99fbbb8c95be46b4c6399d1db376688940 (patch)
treeb4bd76f42259fa9a676b294190f7f79d7c2cf03a /bin/unix/timer.sh
parent005cf5f0fed1d253631e00e228f69d6e3e487771 (diff)
Update timer.sh
Diffstat (limited to 'bin/unix/timer.sh')
-rwxr-xr-xbin/unix/timer.sh62
1 files changed, 62 insertions, 0 deletions
diff --git a/bin/unix/timer.sh b/bin/unix/timer.sh
new file mode 100755
index 0000000..ac9c858
--- /dev/null
+++ b/bin/unix/timer.sh
@@ -0,0 +1,62 @@
1#! /bin/bash
2# Ref: https://superuser.com/questions/611538/611582#611582
3
4SIGNAL=${1:-SIGTERM}
5
6# If SIGNAL is received, switch to next display
7trap 'next_display' $SIGNAL
8#trap 'toggle_timer' SIGTSTP
9# Do not print "^C" when SIGINT caught
10stty -ctlecho
11
12# Hide the cursor
13tput civis
14
15display_list=(STOPWATCH COUNTDOWN PERIOD)
16export DISPLAY=0
17
18next_display() {
19 export DISPLAY=$(( ($DISPLAY + 1) %${#display_list[@]} ))
20}
21
22export stop=
23toggle_timer() {
24 [ "$stop" = true ] && export stop= || export stop=true
25}
26
27# Wait user input
28read -p '? ' input
29
30# Modify input to fit the format that `date` can read
31# s -> sec
32# m -> min
33# h -> hour
34[[ "$input" =~ s && ! "$input" =~ sec ]] && input="$(sed s/s/sec/ <<<"$input")"
35[[ "$input" =~ m && ! "$input" =~ min ]] && input="$(sed s/m/min/ <<<"$input")"
36[[ "$input" =~ h && ! "$input" =~ hour ]] && input="$(sed s/h/hour/ <<<"$input")"
37
38start=$(date +%s) # unix epoch of start
39given=$(date +%s -d "$input") # unix epoch of end
40period=$(( $given - $start )) # seconds for timer
41
42time=0
43while [ $time -ne $period ]; do
44 [ "$stop" = true ] && sleep 0.3 && continue
45
46 time="$(( $(date +%s) - $start ))"
47 case ${display_list[$DISPLAY]} in
48 STOPWATCH)
49 printf '%s\r' "$(date -u -d @$time +%H:%M:%S)"
50 ;;
51 COUNTDOWN)
52 printf '%s\r' "$(date -u -d @$((period - $time)) +%H:%M:%S)"
53 ;;
54 PERIOD)
55 printf '%s\r' "$(date -u -d @$period +%H:%M:%S)"
56 ;;
57 esac
58
59 sleep 0.3
60done
61
62printf "\e[1;31m$(date -u -d "@$time" +%H:%M:%S)"