我正在使用自定义 bash 提示符来显示 git 分支。
一切都在/etc/bash/bashrc
中:
function formattedGitBranch {
_branch="$(git branch 2>/dev/null | sed -e "/^\s/d" -e "s/^\*\s//")"
# tried these:
echo -e "\e[0;91m ($_branch)"
echo -e "\e[0;91m ($_branch) \e[m"
echo -e $'\e[0;91m'"($_branch)"
echo "($_branch)"
echo "$(tput setaf 2) ($_branch) $(tput setaf 9)"
printf "\e[0;91m ($_branch)"
}
# color is set before function call
PS1='\[\033[01;34m\] \[\033[0;91m\]$(formattedGitBranch) \$\[\033[00m\] '
# color is set inside function
PS1='\[\033[01;34m\] $(formattedGitBranch) \$\[\033[00m\] '
问题是,当我在函数中为 $_branch
设置颜色时,到达 EOL 时我的提示将被覆盖:
尝试了所有可能的变体tput
、printf
、$''
表示法。
我通过仅在 PS1
中设置颜色解决了问题:
但是..
- 我想知道为什么它会覆盖我的提示
- 使用函数时如何解决此问题
我正在使用 Gentoo Linux。 GNU bash,版本 4.2.37(1)-release (i686-pc-linux-gnu)
最佳答案
1) 我想知道为什么它会覆盖我的提示
因为每个不可打印的字符都必须通过 \[
和 \]
转义,否则 readline无法正确跟踪光标位置。
You must put
\[
and\]
around any non-printing escape sequences in your prompt.
Without the\[ \]
bash will think the bytes which constitute the escape sequences for the color codes will actually take up space on the screen, so bash won't be able to know where the cursor actually is.
\[
Begin a sequence of non-printing characters. (like color escape sequences). This allows bash to calculate word wrapping correctly.
\]
End a sequence of non-printing characters. -- BashFAQ...note the escapes for the non printing characters, these ensure that readline can keep track of the cursor position correctly. -- ss64.com
2) 使用function
时如何解决此问题
如果您想在输出用于 PS
的函数
内设置颜色,您有两个选择。
要么转义整个函数调用:
PS1='\[ $(formattedGitBranch)\] '
或者replace the non-printing Escape
echo
内的序列。即替换:\[
和\]
与\001
\002
(感谢user grawity!)
echo -e
is not aware bash 的\[
\]
因此你必须用\001
和\002
ASCII 控制代码替换它们将不可打印字符与可打印字符分隔开:function formattedGitBranch { echo -e "\001\e[0;91m\002 ($_branch)"; }
PS1='$(formattedGitBranch)'
关于bash - 自定义 Bash 提示符正在覆盖自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25608184/