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

command linegnome-terminal

I prefer to use terminal and spend most of the time using it. I am searching a way to see time in terminal while I use it parallel. The time would change automatically when it passes. It would be awesome if it would display left to my command prompt.

If this is my command prompt in terminal:

saurav@saurav-P4I45Gx-PE:~$

Then I would like to see clock(time) as:

saurav@saurav-P4I45Gx-PE[06:27:01]:~$

or

saurav@(06:27:01):~$

or any other format. where 06:27:01 is the time. What I want is just to show the time which changes when seconds pass.

So is there any way to achieve this?

Best Answer

  • 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