I think I just found the easiest and cleanest way to add precise dates to my bash prompt:
PS0=">>> \$(date +%T.%3N)\\n$PS0"
PROMPT_COMMAND='echo "<<<" $(date +%T.%3N);'$PROMPT_COMMAND
skip the explanations and see the resluts >>>
The first line add the first date. The one displayed just after the enter button is pressed. It is based on bash 4.4 $PS0 variable. $PS0 works the exact same way as $PS1 except that it is displayed before every command's execution.
The drawback to this method is that it wont work on previous verions of bash. Luckily every recent verions of linnux now ship with bash 4.4.
Run this command to check your bash version and see if you can use $PS0.
bash --version
Next is the date command. We could have used PS0=">>> \t\\n$PS0" as \t gets expanded to the current time in both $PS0 and $PS1. However this would have left us with a second accuracy, which is not that cool. And as you can see in the picture, a second accuracy wouldn't have been that helpful.
The milliseconds by the way are obtained via the %3N flag. %N gives us nanoseconds and %3N rounds this number to 3 digits which gives us milliseconds. I've heard about %N flag not beeing present in OSX's date and also about a fix for this based on brew install coreutils if I remember correctly.
The second line is more tricky. As I said previously, I could have used PS1="<<< \t\\n$PS1". But not only this method can't display milliseconds it also adds a lot of noise in your prompt. If you take a closer look at the picture below you will be able to see two things:
- the background of my terminal has an opacity of
.9so you can try to guess what was behind. - at the second prompt no dates are displayed.
Indeed, this is a bash completion view triggered by a double tab. The first date is not displayed because it is displayed before every command's execution. The second date however would have been displayed if I used the $PS1 method as $PS1 is the prompt string.
$PROMPT_COMMAND is a variable containing a function to execute after each command and before $PS1 is displayed. It is often used to edit the content of $PS1 as in posh-git-bash for example. However I have found that in my case it is a lot more useful to call echo as I wanted to display the date on it's own line anyway. This gives me a very important benefit:
As this doesn't modify $PS1 there are no problems of compatibility with my other prompt tweaks (yes posh-git-bash, I'm talking about you) or scripts that modify the prompt (python's virtualenv for example), as you can see in the picture below.
Finaly I concatenated my echo with the original $PROMPT_COMMAND (with a ; to separate them) so that other commands that I might add get executed as well.
