bash

How to fix terminal prompt not wrapping correctly

Submitted by luxian on Tue, 04/03/2018 - 13:23

On all the servers I manage I tend to change PS1 (Prompt String One) to add a memo of the environment you are on. For example I will display a red [ PROD ] in front of command prompt on production servers to remind ssh users they are on a production server. Development servers get the same treatment, with a [ DEV ] prefix and a blue background. Example with the value used on Ubuntu dev server:

PS1="\e[104m\e[30m[DEV]\e[0m "'${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '

Unfortunately, after doing this, the command prompt didn't wrap correctly at the end of the line. This wasn't noticed in the beginning and then I was too lazy to fix it until today, when I found the fix quite fast on Unix Stackexchange: Terminal prompt not wrapping correctly. The problem is caused by the color sequenced I used:

Non-printable sequences should be enclosed in \[ and \].

And the explanation why this happens:

The reason for the behavior is because bash believes the prompt is longer then it actually is.

Basically, the line will wrapp later than expected because bash thinks the line is longer.

The correct version of command prompt above is:

PS1="\[\e[104m\e[30m\][DEV]\[\e[0m\] "'${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '

 

Tags