Skip to content

Instantly share code, notes, and snippets.

@busterc
Last active January 11, 2020 07:14
Show Gist options
  • Save busterc/260d4bdcb569aae12556 to your computer and use it in GitHub Desktop.
Save busterc/260d4bdcb569aae12556 to your computer and use it in GitHub Desktop.
stopwatch with laps for bash #bash
#!/bin/bash
function stopwatch() {
local n=0
local t=0
local continuing="true"
local lap=1
local key="~"
local pausing="~"
cat <<EOF
* type "p" to pause and "r" to resume
* hit the spacebar to start a new lap
* if paused you will resume with a new lap
* type "q" or "x" or Ctrl-c to stop
EOF
function summary() {
continuing="false" # break the while loop
local elapsed=$(($t-$lap+1))
printf "\r\033[0KLap ${lap}: $n seconds\n"
printf "\nTotal Elapsed: $elapsed seconds\n"
}
trap "summary" SIGINT
while [[ $continuing = "true" ]]; do
key="~"
pausing="~"
printf "\r\033[0KLap ${lap}: $n seconds"
read -s -t 1 -n 1 key
case "$key" in
"")
printf "\r\033[0KLap ${lap}: $n seconds\n"
key=""
n=-1
((lap++))
;;
q|x)
summary
break
;;
p)
function paused() {
read -s -n 1 pausing
case "$pausing" in
"")
printf "\r\033[0KLap ${lap}: $n seconds\n"
key=""
n=-1
((lap++))
;;
q|x)
summary
break
;;
r)
: # noop
;;
*)
paused
;;
esac
}
paused
;;
esac
((t++))
((n++))
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment