3

我基本上是在尝试创建一个具有以下输出的 PS1:

$ ~/Projects/Blah (master):

但是,如果我所在的文件夹不是 Git 存储库,我希望它看起来像这样:

$ ~/Projects/Blah:

这是我目前的 PS1:

export PS1="$ \w \$(__git_ps1): "

当我在 Git 存储库中时,它给了我想要的输出,但是当我在不在 Git 存储库中的文件夹中时,输出如下所示:

$ ~/Projects/Blah :

如果它不是 Git 存储库,我真的不想要那个空间。

有什么方法可以在我的 PS1 中指定吗?

4

4 回答 4

2

使用 逐段构建提示通常要简单得多PROMPT_COMMAND,这是在显示每个提示之前执行的代码。(PS1顺便说一句,不需要导出。)

build_prompt () {
    PS1="$ \w"
    git_info=$(__git_ps1)
    if [[ $git_info ]]; then
        PS1+=" $git_info"
    fi
    PS1+=": "
}
PROMPT_COMMAND=build_prompt
于 2016-05-04T12:08:02.737 回答
2

我最终使用了这个.git-prompt.sh文件。使其工作的步骤:

  1. .git-prompt.sh在您的主目录 ( ) 中创建一个名为的文件~/.git-prompt.sh,并将上面链接中的代码复制到其中。
  2. 在您的.bash_profileor.bashrc文件中,添加以下行:source ~/.git-prompt.sh
  3. 将您的 PS1 更改为:PS1='\n$ \w$(__git_ps1 " (%s)"): '
于 2016-05-04T08:40:52.190 回答
0
export PS1="$ \w \$(__git_ps1): "

我有 __git_ps1 等于git branch 2>/dev/null | grep '*' | sed 's/* \(.*\)/(\1)/'.

将您更改__git_ps1为:

git branch 2>/dev/null | grep '*' | sed 's/* \(.*\)/ (\1)/'

sed注意替换之前的额外空格(\1)

Edit1:由@andlrc 简化__git_ps1,减少一个命令:

__git_ps1() { git branch 2>/dev/null | sed -n 's/\* \(.*\)/ (\1)/p'; }
于 2016-05-04T08:27:52.130 回答
0

准备git_ps1这样的:

git_ps1=$(git branch 2>/dev/null | grep '*')
git_ps1="${git_ps1:+ (${git_ps1/#\* /}) }"
##                  ^space             ^space
## Change the spaces if you like it other ways.

git_ps1会像(master),两端有空格;和一个完整的空字符串 when git_ps1is not set (for non-git dir) 。现在您可以使用该$git_ps1变量将其插入到您喜欢的任何位置。

解释:

git_ps1="${git_ps1:+ (${git_ps1/#\* /}) }"

条件变量赋值

  1. 如果git_ps1设置了,那么它将等于(${git_ps1/#\* /}),否则它将保持为空。

  2. ${git_ps1/#\* /}从开头切掉*and 空间$git_ps1


示例用法:

__git_ps1(){
    git_ps1=$(git branch 2>/dev/null | grep '*')
    git_ps1="${git_ps1:+ (${git_ps1/#\* /})}"
    echo "$git_ps1"
}
if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[00m\]\[\033[01;34m\]\w\[\033[00m\]$(__git_ps1) \[\033[1;32m\]>\[\033[00m\]\[\033[1;32m\]>\[\033[00m\]\[\033[1;32m\]>\[\033[00m\] '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi

这给了我这样的提示: 在此处输入图像描述

于 2016-05-04T10:31:27.583 回答