How to show a clock in terminal prompt

Created: 2022-01-24 | 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:

#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:

 1# "If the PROMPT_SUBST option is set, the prompt string is first subjected to parameter expansion, command substitution and arithmetic expansion."
 2# See: https://zsh.sourceforge.io/Doc/Release/Prompt-Expansion.html
 3setopt PROMPT_SUBST
 4# Clock format
 5# See: Same link above
 6PROMPT='%D{%H:%M:%S} $ '
 7# Set time out of 1 second
 8# See: https://zsh.sourceforge.io/Doc/Release/Parameters.html
 9TMOUT=1
10
11# Executed every TMOUT seconds. 1 second in this example
12TRAPALRM() {
13    # Reset the prompt, so that the clock acts like it's "moving"
14    # See: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#index-reset_002dprompt
15    zle reset-prompt
16}

#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