Bash prompt messed up on arrow up

bashcommand line

I have made some modification to my prompt with use of colors via tput.

It looks like now when I try to do an arrow up lookup after few moves up, the prompt is being cut into half, what I mean by this is:

From this:

PROD mysuer@server1.domain.com:~$ vim .bashrc

To this:

PROD mysuer@servegit rebase origin/add_pool

ctrl + c brings everything back to normal.

I have found some posts indicating that this may be due to the issue with missing escapes for [ however I don't see an issue here:

My code:

#red for prod, green for lab

COLOUR_RESET=$(tput sgr0)
COLOUR_GREEN=$(tput setaf 2)
COLOUR_BLUE=$(tput setaf 6)
COLOUR_YELLOW=$(tput setaf 3)
COLOUR_RED=$(tput setaf 1)
BOLD=$(tput bold)

if [[ $HOSTNAME =~ .*\.domain.com$ ]]; then
  COLOUR=$COLOUR_RED
  PROMPT_TEXT="PROD"
fi

if [[ $HOSTNAME =~ .*\.lab$ ]]; then
  COLOUR=$COLOUR_BLUE
  PROMPT_TEXT="LAB"
fi


MYPROMPT="$COLOUR$BOLD$PROMPT_TEXT$COLOUR_RESET \[\u@$COLOUR$BOLD$(hostname -f)$COLOUR_RESET:\w\]\$ "

PS1=$MYPROMPT

UPDATE:
@KamilMaciorowski has pointed out a similar question although it was not relating to a tput colors.

Best Answer

My answer elsewhere is almost sufficient, you should wrap the output of tput in \[ \].

Almost sufficient, because you already have \[ \] in wrong places; you should get rid of them. man 1 bash says:

\[
begin a sequence of non-printing characters, which could be used to embed a terminal control sequence into the prompt

\]
end a sequence of non-printing characters

This means that e.g. $(hostname -f) should be outside any \[ \]. So either

  • remove \[ and \] from the explicit MYPROMPT definition and replace every =$(tput …) with ='\['"$(tput …)"'\]';

or

  • change only the MYPROMPT definition. I adjusted your original one:

    MYPROMPT="\[$COLOUR$BOLD\]$PROMPT_TEXT\[$COLOUR_RESET\] \u@\[$COLOUR$BOLD\]$(hostname -f)\[$COLOUR_RESET\]:\w\$ "
    # printing                ^^^^^^^^^^^^                 ^^^^                ^^^^^^^^^^^^^^                 ^^^^^^
    # non-pr.   ^^^^^^^^^^^^                ^^^^^^^^^^^^^        ^^^^^^^^^^^^                  ^^^^^^^^^^^^^