I essentially know what the problems is, in that I need to use \[...\] as a way to escape (non-space?) characters, and allow bash to correctly calculate the width of my prompt.

However, I cannot iron out all the problems and have been using trial and error as I don't quite understand where exactly I need all my \[...\] placed.

export PS1="$STARTCOLOR$BACKGROUND\u@\h \[\t\]$ENDCOLOR\w>\$?\$\]"

Is what I am using. The only issue now seems if I use the arrow keys to scroll previous commands for too long the \w>\$?\$\ part of my PS1 will disappear. It happens too if I reverse back with arrow keys after moving forward with previous commands.


2 Answers 2


The problem is that you are using the non-printing markers for something that gets printed out (\t - the timestamp)

export PS1="$STARTCOLOR$BACKGROUND\u@\h \t$ENDCOLOR\w>\$?\$ "

The \[ ... \] is only for surrounding non-printing character sequences, such as colour codes.

  • This has worked...almost. Scrolling arrow keys through past commands will now leave a single character after the prompt. While not ideal, it is drastically more manageable then before, while keeping my custom prompt.
    – Gee_k
    Dec 18, 2020 at 1:14
  • I took off the final ' \] ' at the and of the prompt (non-printing markers), which seems to have finally solved it entirely.
    – Gee_k
    Dec 18, 2020 at 1:22
  • 1
    You're absolutely right, @Gee_k, and I've removed that unbalanced and unnecessary \]. It's strange because I did test before posting and I couldn't get the string to fail
    – roaima
    Dec 18, 2020 at 3:58

So the issue is that you "overuse" \[ and \]. Those should only be used for non-printable character sequences according to the bash manual:

Begin a sequence of non-printing characters.
This could be used to embed a terminal control sequence into the prompt.

Additionally, there is a special syntax you need to use so Bash properly renders tabs: $'\t'.

So in the end, a more or less fixed version of your prompt code would look like this:

#!/usr/bin/env bash

readonly PROMPT_STARTCOLOR='\[\e[0;31m\]'
readonly PROMPT_ENDCOLOR='\[\e[0m\]'
readonly PROMPT_BACKGROUND='\[\e[47m\]'


Note that I've renamed your variables to prevent a possible conflict with your environment.

To use the script:

source <path_to_file>

Related question I asked a while ago: Prompt customization problem with if clause

  • the \t was for the time. It renders as \t here as a blank area without showing the time. Scrolling with arrow keys for too long here also makes the $ prompt disappear.
    – Gee_k
    Dec 18, 2020 at 1:11

You must log in to answer this question.

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