bash - 自定义 Bash 提示符正在覆盖自身

标签 bash command-prompt gentoo

我正在使用自定义 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 时我的提示将被覆盖:

mmmmmmmmmmmmp/rainyday.js (master) $ mmmmmmmm

尝试了所有可能的变体tputprintf$''表示法。

我通过仅在 PS1 中设置颜色解决了问题:

ad@gentoo /tmp/rainyday.js (master) $ mmmmmmm

但是..

  1. 我想知道为什么它会覆盖我的提示
  2. 使用函数时如何解决此问题

我正在使用 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/

相关文章:

linux - 从一个参数和仅一个参数获取输入

linux - 使用 sed 命令的 Jenkinsfile ssh 问题

linux - Gentoo + VICE(commodore 64 模拟器)

mysql - Gentoo无法安装mysql

python - 如何在执行前通过 python 程序显式配置命令提示符?

postgresql - 如何将默认的 postgres super 用户重命名为 "root"?

sql - 无法在 bash 脚本中使用 postgresql 函数

linux - 如何删除特定字符后的字符串中的所有内容?

excel - 从 FTP 站点获取最新文件的批处理/宏代码

java - 仅使用命令提示符启动 Jetty 8 服务器