How to show a clock in terminal prompt

Created: 2022-01-24 | 2 min


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:

on.

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

#Reference