Search code examples
macosterminalzshoh-my-zsh

Adding timestamp to each line on Zsh


I just fresh installed Sierra and wanted to use zsh with oh-my-zsh and power shell...

I ended up with a terminal like this:

enter image description here

But I want to add a timestamp to every output. Semething linke:

[14:23] acytryn ~ Projects %

Is there a way to do this with zsh?


Solution

  • I've found it more non-destructive to actually prepend the time to the existing prompt without overriding it completely. This makes it work with any existing theme without interfering with its styling.

    Add this at the end of your .zshrc file. You can type the command nano ~/.zshrc to edit it using nano:

    PROMPT='%{$fg[yellow]%}[%D{%f/%m/%y} %D{%L:%M:%S}] '$PROMPT
    

    I use cloud theme, so this gives me:

    enter image description here

    It retains the current theme. You can also add some styling to the timestamp, by changing the color, or even the format. You may refer to the official Zsh Date and Time formatting linked here: https://zsh.sourceforge.io/Doc/Release/Prompt-Expansion.html#Date-and-time. This uses Linux's strftime3 (https://man7.org/linux/man-pages/man3/strftime.3.html) to format the Date (%D) string.

    Make sure to reload your .zshrc file by typing:

    . ~/.zshrc
    

    or

    source ~/.zshrc