我希望我的命令提示符在我的提示字符串 1 (PS1) 中显示当前分支。该命令在 git 存储库中有效,但当不在 git 存储库中时,我收到正确的错误消息:fatal: Not a git repository (or any of the parent directories): .git
我想抑制该错误消息,否则每次我切换目录并且我不在 git 存储库中时,该错误都会打印到终端。
我阅读了通过将错误输出发送到空设备 /dev/null
来抑制终端输出,但错误消息仍然打印在我的终端中。
这是我用来提取当前分支的命令:
git 分支 2>/dev/null | grep '*' |剪切 -d ' ' -f2
。
最佳答案
确保在 $()
构造中转义 $
,以便在生成每个提示时重新计算它,而不是仅在 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 $
关于bash - 不在 git 存储库中时无法抑制 git 分支错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50615081/