Skip to content

Instantly share code, notes, and snippets.

@noureddin
Created August 24, 2020 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noureddin/e47443b66d7efae84a899ac576a81afb to your computer and use it in GitHub Desktop.
Save noureddin/e47443b66d7efae84a899ac576a81afb to your computer and use it in GitHub Desktop.
A simple stopwatch in Bash
#!/bin/bash
replace_line() { printf "\r\e[K$1 " ${@:2}; }
wait_enter() { read -s; }
now() { echo $( date +%s.%N ); }
time_format() {
a=$( printf "%.2f " $1 )
m=$( printf "%d" $( echo $a / 60 | bc ) )
if [ "$m" -ne "0" ]
then
s=$( printf "%05.2f" $( echo $a % 60 | bc ) )
replace_line "%s:%s " $m $s
else
s=$( printf "%.2f" $( echo $a % 60 | bc ) )
replace_line "%s " $s
fi
}
eechoo() {
while sleep 0.05
do
d=$( echo $(now) - $1 | bc )
replace_line "%s " $( time_format $d )
done
}
t=$( now )
eechoo $t &
while wait_enter
do
kill %%
d=$( echo $(now) - $t | bc )
replace_line "%s PAUSED " $( time_format $d )
wait_enter
d2=$( echo $(now) - $t | bc )
t=$( echo $t + $d2 - $d | bc )
eechoo $t &
done 2>/dev/null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment