在 Linux 上显示当前分支和着色(如 Windows 上的 Git Bash)

sas*_*alm 7 linux git git-bash

在 Windows 上的 Git Bash 上,我得到了很好的着色,并显示了当前分支,如下所示:

在此处输入图片说明

如何在 Linux 上获得相同的颜色和提示?在 Linux 上,我使用常规终端,它不显示当前分支。

Arp*_*Roy 6

如果您想保留现有 Linux 终端的相同颜色并显示当前 git 分支,您可以将以下内容添加到默认 PS1.

PS1 基本上告诉你的 bash 提示符要显示什么。参考:如何在 Linux 中更改/设置 bash 自定义提示符 (PS1)

我使用的是 Ubuntu 20.04,默认的 PS1 位于if [ "$color_prompt" = yes ]; then~/.bashrc 文件中。

脚步:

  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)/'
}
Run Code Online (Sandbox Code Playgroud)
  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
Run Code Online (Sandbox Code Playgroud)

整个事情应该看起来像这样:

#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
Run Code Online (Sandbox Code Playgroud)
  1. 保存更改并重新启动终端。

它应该看起来像这样: 带有 git 分支的终端


Nog*_*eke 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\] "
Run Code Online (Sandbox Code Playgroud)

其外观示例:

在此输入图像描述

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