在终端中添加当前的 git 分支

hay*_*ayd 21 command-line prompt git ps1

如何配置终端以显示当前的 git 分支?

我想看到第二行而不是第一行:

andy@bob:~/my_projects/project_x$ 
(master)~/my_projects/project_x$
Run Code Online (Sandbox Code Playgroud)

我不想再跑git status去看我现在在哪个分支了!

hay*_*ayd 34

您可以将以下代码添加到您的.bashrc文件中:

parse_git_branch() {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
PS1="${debian_chroot:+($debian_chroot)}\u@\h:\w\$(parse_git_branch) $ "
Run Code Online (Sandbox Code Playgroud)

您可以移动这些组成部分以根据您的喜好进行配置,例如预先添加$(parse_git_branch)而不显示我使用的 user@computer 部分:

PS1="\$(parse_git_branch)${debian_chroot:+($debian_chroot)}\w$ "
Run Code Online (Sandbox Code Playgroud)

其中显示:

(master)~/my_projects/project_x$ 
Run Code Online (Sandbox Code Playgroud)

另请参阅:这个 PS1 变量在 .bash_profile 文件中有什么作用?