Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding ANSI color escape sequences to a bash prompt results in bad cursor position when recalling/editing commands

If I set my command prompt like:

export PS1='\033[0;33m[\u@\h \w]\$ \033[00m'

The color of the prompt will be yellow and everything after the '$' character will be the default terminal color. This is what I expect. However, If I recall a command line and attempt to edit it, moving the cursor -- either UpArrow/Ctrl-A (set -o emacs) or ESC K (set -o vi) if the command line I'm trying to edit is long enough, the cursor is not positioned at the beginning of the command. Typing either Ctrl-A (set -o emacs) or ^ (set -o vi) will not move the cursor to what I'm seeing as the beginning of the recalled line on the screen. Similarly, attempting to position the cursor to the end of the line (Ctrl-E or $, depending) results in it being placed several characters past what appears to be the end of the line. It looks like bash is getting confused by the escape characters I've added to the prompt. Is this just something I'll have to deal with, changing my prompt to a monochromatic one when I wish to edit recalled lines, or is there a way to get bash to correctly allow the editing of recalled commands with a colorful prompt?

like image 392
Xaq Avatar asked Jul 02 '13 18:07

Xaq


People also ask

What is ANSI escape sequences Python?

ANSI escape sequences are a standard for in-band signaling to control cursor location, color, font styling, and other options on video text terminals and terminal emulators. Certain sequences of bytes, most starting with an ASCII escape character and a bracket character, are embedded into text.

How do I change the $PS1 prompt in Linux bash?

You can change the BASH prompt temporarily by using the export command. This command changes the prompt until the user logs out. You can reset the prompt by logging out, then logging back in.


1 Answers

You need to enclose the non-printing characters in \[ ... \] so that bash knows to ignore them when computing the length of the prompt:

export PS1='\[\033[0;33m\][\u@\h \w]\$ \[\033[00m\]'
like image 152
chepner Avatar answered Oct 13 '22 05:10

chepner