How to show a running clock in terminal before the command prompt

I'm not sure that is so simple to achieve this using the default bash shell (but I'm not saying that it's impossible). You will probably need a command/function which is able to refresh the command prompt every second without interfering with anything you type on the prompt.

The Z shell (zsh) has a built-in command, called zle, which, when used with the reset-prompt argument, forces the prompt to be re-expanded, then redisplays the edit buffer.

If you want to try it, use the following steps:

  1. Install Z shell with this command:

    sudo apt-get install zsh
    
  2. When you run zsh for the first time, choose 0 when you are asked.

  3. Edit the ~/.zshrc file and add the following lines:

    setopt PROMPT_SUBST
    PROMPT='%B%F{red}%n@%m%f%F{yellow}[%D{%L:%M:%S}]%f:%F{blue}${${(%):-%~}}%f$ %b'
    TMOUT=1
    
    TRAPALRM() {
        zle reset-prompt
    }
    

    Save the file and close it.

  4. In your terminal, when you are still using zsh, run source ~/.zshrc, or simply zsh, to reset your prompt. Now your prompt should look like:

    saurav@saurav-P4I45Gx-PE[1:25:21]:~$
    

    with some colors.

  5. If you like it, run chsh -s /bin/zsh to change your current shell to /bin/zsh (a re-login is required for this change to take effect).

  6. Run exit if you want to exit from zsh shell.

Here is a 15 second screencast from my terminal:

running clock in terminal before the command prompt


If you want to display running time in your terminal you can use this command. It will display time in the upper right side of your terminal.

  while sleep 1;do tput sc;tput cup 0 $(($(tput cols)-11));echo -e "\e[31m`date +%r`\e[39m";tput rc;done &

enter image description here

But note that displaying time using this command sometime may overlap the text present in terminal. So use this command with little caution.

Another way may be using control character in in the PS1

[guru@guru-pc ~]$  PS1='\[\u@\h \T \w]\$'

[guru@guru-pc 11:06:16 ~]$

But in this method your time will refresh only after pressing enter.

If you want to above method permanent add the above command(the one you like or both) in your ~.bashrc file.


If all you want to do is show a clock, just use date:

while :; do date +%r; sleep 1 ; done

That will show the time every second until you stop it with CtrlC. If you want it to be on the same line (the above will print a new line every second), do this instead:

while :; do printf '%s\r' "$(date +%r)"; sleep 1 ; done