【问题标题】:Show current branch and coloring on Linux (like Git Bash on Windows)在 Linux 上显示当前分支和着色(如 Windows 上的 Git Bash)
【发布时间】:2017-07-01 17:34:06
【问题描述】:

在 Windows 上的 Git Bash 上,我得到了漂亮的颜色,并显示了当前分支,如下所示:

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

【问题讨论】:

  • 有几十个包有花哨的提示设置。选择你喜欢的;确保它适用于您喜欢的 shell。 Arpit 下面提到了 zsh,需要从 bash 切换到 zsh。

标签: linux git git-bash


【解决方案1】:

如果你使用的是 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\] "

外观示例:

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

【讨论】:

  • 我试用时看起来像(master)$[00 m
  • @sashoalm 我的错,我复制时有多余的空间,现在已修复。
  • 你的函数的名字是show_git_branch,然后你使用一个叫做parse_git_branch的东西。
  • @cheb1k4 已修复
【解决方案2】:

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

PS1 基本上告诉您的 bash 提示符要显示什么。 参考:How to Change / Set up bash custom prompt (PS1) in Linux

我使用的是 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)/'
}
  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
  1. 保存更改并重新启动终端。

它应该看起来像这样: Terminal with git branch

【讨论】:

    猜你喜欢
    • 2017-06-20
    • 2017-07-31
    • 1970-01-01
    • 2010-11-27
    • 2015-04-11
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多