Simple Countdown Timer and Stopwatch with Laps for Bash

There are a lot of decent, small shell scripts for creating a simple timer or simple stopwatch. Yet, I needed a bit more than the ones I found on Google, so of course, I made some of my own.

My simple stopwatch for Bash lets you create laps, pause and gives you a total elapsed time. Keep in mind, it’s all presented in seconds.

stopwatch with laps for 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
}
view raw stopwatch.sh hosted with ❤ by GitHub

My simple timer for Bash just countdowns the number of seconds you provide and then beeps. Like my stopwatch script, it’s all based on seconds so that there aren’t a bunch of command line arguments to deal with.

countdown timer for bash

#!/bin/bash
function timer() {
if [[ $1 -lt 1 ]]; then
cat <<EOF
Usage: timer <seconds>
EOF
return 1
fi
local n="$1"
while [[ $n -gt 0 ]]; do
printf "\r\033[0K==> $n"
sleep 1
((n--))
done
printf "\r\a"
}
view raw timer.sh hosted with ❤ by GitHub