MacOS – When I set an export PROMPT_COMMAND, it changes the terminal settings

bashmacosterminal

So, I wanted to add a timestamp to my terminal prompt and I followed this askUbuntu answer to do so. And it works fine. In my terminal preferences I have set the new tab to open the present working directory. After adding the export PROMPT_COMMAND in .bash_profile, however my new tab opens the default directory. When I comment out that line, it works normally again.

Why does this happen? How can I get timestamps on my terminal prompt without messing up my new tab settings

Best Answer

The problem is that PROMPT_COMMAND is used by the system bash to enable per-session history. If you look at /etc/bashrc_Apple_Terminal you see

# Note that this uses PROMPT_COMMAND to enable per-session history
# the first time for each new session. If you customize PROMPT_COMMAND
# be sure to include the previous value. e.g.,
#
#   PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND; }your_code_here"

So if you want to follow the recommendations in the advice you've linked to you are better off just using

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

or similar. If you really want to use PROMPT_COMMAND

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

but the prompt will get messed up if you navigate back in time with Ctrl-P.