How to show a clock in terminal prompt
| 2 min read
How to show a clock in your terminal prompt.
Goal
In terminal, some times I want (and need) to see the exact time when I am running a command. So, two things to accomplish:
- Show the current time in terminal, this should work as an actual clock moving. E.g. 13:32:54, then 13:32:55, and so on.
- Take a snapshot of the exact time when a command was run. E.g. I ran this command at 13:32:55 exactly, so that I can revisit my terminal and see when that happened.
Approach
Avoid bloated plugins / solutions, since all I want to have is literally a clock in my terminal prompt, the simpler the better, considering I run shell with zsh on Ubuntu 20.04.3 LTS.
After some research, found this in askubuntu.com: https://askubuntu.com/a/360172 . This answer is well explained, I just adjusted some of the styles that worked for me.
The script
This is the simplified version of the script in my .zshrc file that should hopefully help my future me (and probably
others) to see what’s needed:
# "If the PROMPT_SUBST option is set, the prompt string is first subjected to parameter expansion, command substitution and arithmetic expansion."
# See: https://zsh.sourceforge.io/Doc/Release/Prompt-Expansion.html
setopt PROMPT_SUBST
# Clock format
# See: Same link above
PROMPT='%D{%H:%M:%S} $ '
# Set time out of 1 second
# See: https://zsh.sourceforge.io/Doc/Release/Parameters.html
TMOUT=1
# Executed every TMOUT seconds. 1 second in this example
TRAPALRM() {
# Reset the prompt, so that the clock acts like it's "moving"
# See: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#index-reset_002dprompt
zle reset-prompt
}
Results
In terminal, clock should show like so:
13:49:00 $ date
Mon 24 Jan 2022 01:49:00 PM -05
13:49:04 $ date
Mon 24 Jan 2022 01:49:04 PM -05