I changed my bash prompt to this:

PS1="\[\033[1;31m[\[\033[1;33m\$(date +%H:%M)\[\033[1;31m] \u:\[\033[1;32m\W\[\033[1;37m\$\[\033[0m\] "

Sorry for the long line, it is mostly due to colors. Basically when I hit the up arrow to go back in Bash history the prompt disappears and everything screws up. It is similar to this question but I don't know if a \[ is missing and where.

up vote 9 down vote accepted

Let's clean it up a bit and make it more portable. In general, it's best to use tput to generate the control sequences instead of hard coding them, as described in Bash FAQ 53. This way it is much easier to find your missing \].

red=$(tput setaf 1)
green=$(tput setaf 2)
yellow=$(tput setaf 3)
white=$(tput setaf 7)
reset=$(tput sgr0)
PS1="\[$red\][\[$yellow\]\A\[$red\]] \u:\[$green\]\W\[$white\]\$\[$reset\] "

Note that I replaced your date invocation with the built-in prompt escape \A that displays the same thing (24-hour time in HH:MM format).

There is one caveat with this approach as described in the linked Bash FAQ, where the output would be garbled if any of the tput control sequences output something that happened to contain a prompt escape. I have never run into that issue so I generally ignore it.

  • 2
    Thank you! I didn't know of tput. This way everything is more clear and readable. Thanks! – rubik Aug 14 '12 at 18:06
  • 2
    Wow it works very well. I just added bold_style=$(tput bold) and \[$bold_style\] at the start of the string to make everything bold like in my question. – rubik Aug 14 '12 at 18:13

You have unbalanced your \[ and \]'s. Control sequences need to be wrapped in them, so that bash knows they don't actually occupy any space in your terminal.

Try this:

PS1="\[\033[1;31m\][\[\033[1;33m\]\$(date +%H:%M)\[\033[1;31m\]] \u:\[\033[1;32m\]\W\[\033[1;37m\]\$\[\033[0m\] "

@jw013's solution is even better, though, as it's much cleaner.

  • Oh I hadn't understood that every control sequence needed to be wrapped like that. Thanks! – rubik Aug 14 '12 at 18:04

The ASCII table has a reference of colors, bold, italic, and etc.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.