Adding timestamps to terminal prompts?

Add this line to the ~/.bashrc file:

export PROMPT_COMMAND="echo -n \[\$(date +%H:%M:%S)\]\ "

So the output will be something like:

[07:00:31] user@name:~$

My solution was to use http://bashrcgenerator.com/ to generate this PS1 line to put in .bashrc:

export PS1="\t [\u@\h \W]\\$ \[$(tput sgr0)\]"

Which will look like

13:05:54 [chad@work-laptop:~/Downloads]$ ls -al

Using PROMPT_COMMAND messes up the history for me. When a longer line comes up while cycling through the history, it cuts off the end of the prompt by the same number of characters as the timestamp that was added to the front. e.g.

13:14:38 [chad@work-laptop:~/Doexport PROMPT_COMMAND="echo -n \[\$(date +%H:%M:%S)\\] "

And this line can't be edited because it does not display the characters in the right place, as in you aren't typing where it looks like you're typing.

I'm guessing it could be done with PROMPT_COMMAND, maybe by using that [$(tput sgr0)] part, but PS1 works.


Instead of adding the date to the prompt itself, you could add the date just before your prompt by placing the following line at the top of your .bashrc. For it work you will also need to install cowsay. It's a fun way of displaying the date while keeping a short prompt:

cowsay "Welcome $USER! It's now $(date '+%A %B %d %Y %r')"

In its current form it will work on anyone's system without amendment as it reads the $USER and the date variable from the current environment.

enter image description here

Tags:

Bash