简体   繁体   中英

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?

您需要在\\[ ... \\]包含非打印字符,以便bash在计算提示的长度时知道忽略它们:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM