How to show current time in mac terminal prompt?

I have this:

PS1+="\D{%H:%M:%S}";

But this displays the time the prompt started. I want the prompt to show the current 12 hour (not 24 hours) time live (so it keeps changing, and then when a command is made, save that time before going to the next prompt (so, without pressing enter / return on the keyboard). So the time the command was made is saved and visible too.

Is this live updating of a time-based prompt possible?


Solution 1:

Simple answer: \T is the code for 12hr time in HHH:MM:SS. So, you'll get:

$ export PS1+="\T"
08:56:25 $
08:56:26 $
08:56:28 $
08:56:30 $

In the case you have the PS1+ is appending onto an earlier configured PS1 variable - you'll need to modify to your needs.

This is a live variable in my version of bash on High Sierra. I copied and pasted above hitting enter to show the seconds incrementing.

Solution 2:

If you are using a bash shell, add the following line to the .bashrc file (not the .bash_profile file).: export PROMPT_COMMAND="echo -n \[\$(date +%H:%M:%S)\]\ "

I just tested this and it works fine. Gives you a prompt like so; [20:58:36]$

This question was asked on StackExchange Ask Ubuntu. The answer was given here. It requires using the z-shell which I know you wish to avoid. Maybe this method is faster.