Skip to content

Instantly share code, notes, and snippets.

@burik666
Last active April 12, 2021 02:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save burik666/fdeaeb8639795483bfa2abab338ad29d to your computer and use it in GitHub Desktop.
Save burik666/fdeaeb8639795483bfa2abab338ad29d to your computer and use it in GitHub Desktop.
bash: print command execution time and exit code.
function __timer_now {
printf %s "${EPOCHREALTIME//\./}"
}
function __timer_start {
timer_start=${timer_start:-$(__timer_now)}
}
function __timer_stop {
local delta_us=$(($(__timer_now) - timer_start))
local us=$((delta_us % 1000))
local ms=$(((delta_us / 1000) % 1000))
local s=$(((delta_us / 1000000) % 60))
local m=$(((delta_us / 60000000) % 60))
local h=$((delta_us / 3600000000))
# Goal: always show around 3 digits of accuracy
if ((h > 0)); then timer_show=${h}h${m}m
elif ((m > 0)); then timer_show=${m}m${s}s
elif ((s >= 10)); then timer_show=${s}.$((ms / 100))s
elif ((s > 0)); then timer_show=${s}.$(printf %03d $ms)s
elif ((ms >= 100)); then timer_show=${ms}ms
elif ((ms > 0)); then timer_show=${ms}.$((us / 100))ms
else timer_show=${us}us
fi
unset timer_start
}
function __print_status {
exit_code="$?"
__timer_stop
local PS_RIGHT="[$timer_show] "
local PS_RIGHT_NC="$PS_RIGHT"
if [ "${exit_code}" -ne 0 ]; then
PS_RIGHT="\e[01;31m${exit_code}\e[00m $PS_RIGHT"
PS_RIGHT_NC="${exit_code} $PS_RIGHT_NC"
fi
tput sc
echo -ne "\r"
tput cuf $(($(tput cols) - ${#PS_RIGHT_NC}))
echo -ne "${PS_RIGHT}"
tput rc
}
trap '__timer_start' DEBUG
PROMPT_COMMAND=__print_status
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment