How to customize PS1 properly?

I customized my bash with this in my bashrc

export PS1="e[0;36mhe[m e[0;33mw/e[m e[0;31mn$ →e[m  "

So I get something like this (with colors) :

Ahuri ~/Public/ 
$ →

But I am having problems with long commands. When I write a very long command that is longer than a line it starts overwriting my first line

Example :

Ahuri ~/Public/ 
$ → ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If I continue to add “^” I get:

Ahuri ~/Public/ 
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

my “$ →” is overwritten, and then the whole line gets overwritten.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

There is no issue with the n. This is yet again the old escape sequence length problem: e[0m and similar do not contribute to the actual length of the prompt, so you have to enclose them in [..] to indicate this to the interpreter:

PS1="[e[0;36m]h[e[m] [e[0;33m]w/[e[m]n [e[0;31m]$ →[e[m]  "

Method 2

A simpler option is to use the tput sequences:

export PS1='[$(tput setaf 4)]h[$(tput sgr0)] [$(tput setaf 3)]w/[$(tput sgr0)]n[$(tput setaf 1)]$ →[$(tput sgr0)] '

The [ and ] enclose the terminal control sequences inserted by the command substitions ($(tput … )) so that the shell does not count them as printable output.
Using the command substitutions rather than hardwiring stuff further ensures that you get the right control sequences for whatever your terminal type is.

Method 3

Use $PROMPT_COMMAND to display the additional line so you have no n in $PS1.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x