Skip to content

Instantly share code, notes, and snippets.

@mkoura
Created June 25, 2025 16:30
Show Gist options
  • Save mkoura/256e0e2b81142ea6a883bce080b50812 to your computer and use it in GitHub Desktop.
Save mkoura/256e0e2b81142ea6a883bce080b50812 to your computer and use it in GitHub Desktop.
Last command's wall time in the Bash prompt?
# Prompt timer using only Bash internals (no traps or external commands).
# Displays how long the last command took if it was 5 seconds or more.
__timer_stop() {
if [ -z "${__timer_start_sec:-}" ]; then
# If `__timer_start_sec` was already cleared, clear `__timer_show` as well, so we don't
# keep showing an outdated timer.
unset __timer_show
return
fi
__timer_show="$((SECONDS - __timer_start_sec))"
unset __timer_start_sec
}
# This is run in a subshell (via PS1), so we cannot unset global vars here.
__timer_echo() {
if [ "${__timer_show:-0}" -ge 5 ]; then
echo "[last: ${__timer_show}s] "
fi
}
# Trick to start the timer at each prompt without using traps or changing PS0 appearance.
# We exploit parameter expansion and $USER (any existing variable works).
PS0='${USER:${__timer_start_sec:=$SECONDS}:0}'
# Run stop function before each prompt.
PROMPT_COMMAND="__timer_stop"
# Show timer in prompt if applicable.
PS1='$(__timer_echo;)'"[\u@\h \W]\$ "
@mkoura
Copy link
Author

mkoura commented Jun 25, 2025

Will show prompt like

[last: 11s] user@machine ~$

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment