bash - 不在 git 存储库中时无法抑制 git 分支错误

标签 bash git

我希望我的命令提示符在我的提示字符串 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/

相关文章:

linux - 如何在循环中更改文件名?

bash - $做什么?和 $# 在 Shell 脚本中代表什么?

regex - 重命名文件或移动文件(如果在 Linux bash 中以逗号分隔)

git - 无法通过SSH克隆/推送

ruby - 在 OS X Lion : How do I edit Bash_Profile? 上安装 Postgres 的路径问题

linux - 此脚本不会按年龄正确排序

git - 当 rebase 需要 merge 时应采取的正确步骤

GIT 撤消不是最近的提交,重新设置所有提交的基础

git 在子模块中添加远程

git - 致命的 : Pathspec 'autoload_classmap.php' is in submodule 'module/CocktailMakerModule'