不在git存储库中时无法抑制git branch错误

时间:2018-05-31 00:31:57

标签: bash git

我希望我的命令提示符在我的提示字符串1(PS1)中显示当前分支。该命令在git存储库中有效,但当不在git repo中时,我收到正确的错误消息:fatal: Not a git repository (or any of the parent directories): .git

我想压缩该错误消息,否则每次切换目录时我都不在git repo中,该错误会打印到终端。

我读到了通过向空设备/dev/null发送错误输出来抑制终端输出,但错误信息仍会打印在我的终端中。

这是我用来提取当前分支的命令:

git branch 2>/dev/null | grep '*' | cut -d ' ' -f2

1 个答案:

答案 0 :(得分:4)

确保转义$构造中的$(),以便在生成每个提示时重新评估它,而不是仅在设置PS1变量时进行评估。

以下是我在实践中的样子:

# Set PS1
$ PS1="\$(git branch 2>/dev/null | grep '*' | cut -d ' ' -f 2) $ "

# Currently in directory that is not a Git repository, change into one.
 $ cd dotfiles/

# Git branch is then displayed in the prompt, leave the directory.
master $ cd ..

# No git branch displayed, change back into it for good measure.
 $ cd dotfiles/

# Branch is displayed again.
master $