在Linux下显示当前分支和颜色(类似于Windows中的Git Bash)

10
在 Windows 上的 Git Bash 中,我可以看到很好的配色和当前分支,就像这样:enter image description here。如何在 Linux 上获得相同的配色和提示呢?我使用常规终端,在 Linux 上它不会显示当前分支。

有许多带有花哨提示设置的软件包。选择你喜欢的任何一个;确保它适用于你喜欢的shell。Arpit在下面提到了zsh,这需要从bash切换到zsh。 - torek
2个回答

7
如果您想保留现有Linux终端的相同着色,并显示当前的Git分支,您可以将以下内容添加到默认的PS1中。
PS1基本上告诉您的bash提示符要显示什么。 参考:如何在Linux中更改/设置bash自定义提示符(PS1) 我正在使用Ubuntu 20.04,而默认的PS1位于~/.bashrc文件中的if [ "$color_prompt" = yes ]; then下面。
步骤:
  1. 打开~/.bashrc文件并找到if [ "$color_prompt" = yes ]; then
  2. 在if语句之前定义以下bash函数(感谢@Nogoseke),您可以在文件中的任何位置定义它,只要在PS1值之前即可。
#show git branch
show_git_branch() {
   git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}

更新PS1值如下:
if [ "$color_prompt" = yes ]; then
    PS1="${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] \[\033[31m\]\$(show_git_branch)\[\033[00m\]$ "
else
    PS1="${debian_chroot:+($debian_chroot)}\u@\h:\w \$(show_git_branch)\$ "
fi

整个东西应该看起来像这样:
#show git branch
show_git_branch() {
   git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}

if [ "$color_prompt" = yes ]; then
    PS1="${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] \[\033[31m\]\$(show_git_branch)\[\033[00m\]$ "
else
    PS1="${debian_chroot:+($debian_chroot)}\u@\h:\w \$(show_git_branch)\$ "
fi

保存更改并重新启动您的终端。
它应该看起来像这样: 带有 git 分支的终端

3
如果你正在使用bash,
我在我的~/.bashrc文件中使用以下内容:
show_git_branch() {
   git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
 }
 export PS1="\[\033[0;37m\]\u@\h\[\033[0;37m\] \w \[\033[31m\]\$(show_git_branch)\[\033[00m\]$\[\033[00m\] "

一个示例:

enter image description here

您只需要将代码添加到您的 .bashrc 文件中并运行 source ~/.bashrc


这段话是关于在Linux系统下,如何将一段代码加入到.bashrc文件中,并使其生效。

当我尝试时,它看起来像(master)$[00 m - sashoalm
1
@sashoalm 不好意思,我复制时多了一个空格,现在已经修复了。 - Nogoseke
你的函数名称应该为 show_git_branch,然后你使用一个叫做 parse_git_branch 的东西。 - cheb1k4
@cheb1k4 已修复。 - Nogoseke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接