8

I have a custom bash prompt that colours my username, hostname and current working directory. The colours display correctly, however when I type a command line that needs to wrap, the terminal does not start a new line, and writes over the beginning of my command. This occurs on RHEL 4 and Debian.

This question details a similar problem on OS X; it would seem that this is an issue with incorrectly terminated control sequences, however I can't see what could be causing this, as I am using $(tput) codes everywhere, rather than hand crafting my codes. Snippet below - is anyone able to advise what I am doing wrong?

# Control codes

COL_RST=$(tput sgr0)  # Remove all colour formatting
COL_BRIGHT=$(tput bold) # Emphasise

# Foreground
COL_G=$(tput setaf 2) # Green
COL_Y=$(tput setaf 3) # Yello
COL_B=$(tput setaf 4) # Blue

COL_USR=${COL_Y}${COL_BRIGHT}
COL_PWD=${COL_B}${COL_BRIGHT}
COL_HST=${COL_G}${COL_BRIGHT}

# Set prompt
PROMPT="${COL_USR}\u${COL_RST}@${COL_HST}\h${COL_RST}:${COL_PWD}\W${COL_RST}"

# Put it all together....
PS1="[$PROMPT]\$ "

export PS1

1 Answer 1

8

Wrap each of your color variables in escaped square brackets:

\[${COL_USR}\]

or

COL_USR="\[${COL_Y}${COL_BRIGHT}\]"

That tells Bash that these are to be considered zero-width.

This is exactly as described in the question you linked to. If you do the following command, you'll see that your variable contain similar character sequences to the "handcrafted" ones. Using tput only makes things portable to multiple $TERM types, it doesn't affect the length of the code sequences. It is that length that is throwing things off.

echo ${COL_USR} | hexdump -c
1
  • one tip: these [ ... ] sequences can't be nested. Now fixed in my bash prompt code at serverfault.com/a/479718/79266 (shows git branch, host, etc, and red prompt for production servers).
    – RichVel
    Apr 8, 2013 at 7:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .