Created
June 25, 2025 16:30
-
-
Save mkoura/256e0e2b81142ea6a883bce080b50812 to your computer and use it in GitHub Desktop.
Last command's wall time in the Bash prompt?
This file contains hidden or 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
# 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]\$ " |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Will show prompt like
[last: 11s] user@machine ~$