Skip to content

Instantly share code, notes, and snippets.

@nchammas
Forked from esoupy/Timer.sh
Last active August 29, 2015 14:08
Show Gist options
  • Save nchammas/c8f738e2bf6962b3ffe3 to your computer and use it in GitHub Desktop.
Save nchammas/c8f738e2bf6962b3ffe3 to your computer and use it in GitHub Desktop.
A simple timer / stopwatch implemented as a bash function.
#!/bin/bash
# Display the duration between timer start and stop.
#
# Usage: timer {start|stop} [format]
#
# Example:
#
# timer start
# <script_commands>
# timer stop [format]
timer() {
local cmd="$1"
local timer_format
if [[ -n "$2" ]]; then
timer_format="$2"
else
timer_format='%-Hh%-Mm%-Ss'
fi
case $cmd in
start)
# This can't be local because we need it to persist across calls.
_timer_StartSecs=$(date +'%s')
;;
stop)
if [[ ! $_timer_StartSecs ]]; then
echo "$FUNCNAME did not record a start." >&2
return 1
fi
local _timer_StopSecs=$(date +'%s')
local DiffSecs=$(($_timer_StopSecs-$_timer_StartSecs))
local TimeLapse=$(date -u -d@"$DiffSecs" +"$timer_format")
echo "$TimeLapse"
;;
*)
echo "$FUNCNAME: Invalid command '$cmd'." >&2
return 1
;;
esac
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment