Search code examples
bashprompt

bash prompt line setting issue


I am using xshell to connect a cloud service of centos, and I set the $PS1 value in /etc/bashrc as \e[0;34m[\u@\h \W]$ \e[m which makes my promt a blue color so that I can tell which is my command input and which is the output.

However, this prompt could not automatically add a new line if my command is more than one line. If one line is full, it just starts padding from the left of the same line. You can see the screenshots as follows:

enter image description here

enter image description here

What I want is that the command can automatically add a new line when one line is full.

I tried \n but that just add a new line before command which is not the effect I want.

Now I tried PS1='[\e[0;34m[\u@\h \W]$ \e[m]', the effect is like: enter image description here

enter image description here


Solution

  • bash can't tell how much space your prompt actually occupies on screen, because the ANSI escape sequences that set colors don't take any space. You need to enclose them (and only them) inside \[...\] to tell bash as much.

    PS1='\[\e[0;34m\][\u@\h \W]$ \[\e[m\]'
    

    bash already knows how to handle its own escape sequences \u, \h, and \W. The ANSI escape sequences only have special meaning to the terminal.

    That is, \u et al are expanded before bash tries to determine how many characters are in the prompt. For all it knows, \e, [, 0, ;, 3, 4, and m will all be displayed literally as single characters. The terminal sees them, and instead of displaying them, changes the color used to print the following characters.