-
-
Save nchammas/c8f738e2bf6962b3ffe3 to your computer and use it in GitHub Desktop.
A simple timer / stopwatch implemented as a bash function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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