【问题标题】:Git branch name in prompt提示中的 Git 分支名称
【发布时间】:2013-07-23 13:16:33
【问题描述】:

我可以在 shell 提示符中显示 git 分支名称。但是每当我使用屏幕时,我都会得到 ​​p>

bash: parse_git_branch: command not found

并且没有显示 git 分支。 请帮助我在屏幕会话中也得到这个。

我的 .bash_profile 中有以下内容。

parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/
}

export PS1="[\W\$(parse_git_branch)]$ "

我没有.git-completion.bash

系统规格:

  • 操作系统:OSX 10.8.4
  • 终端和 iTerm2
  • 屏幕版本:4.00.03 (FAU) 2006 年 10 月 23 日

【问题讨论】:

  • 如何自定义提示?你能给你的 PS1 字符串吗?
  • .git-completion.bash 文件在您的主 shell 中的来源(即没有屏幕?)

标签: bash git gnu-screen


【解决方案1】:

我在屏幕下运行时遇到了同样的问题,并且能够通过将 parse_git_branch() 函数的定义从 .bash_profile 移动到 .bashrc 来解决。

【讨论】:

  • 可以从.bash_profile移动或复制到.bashrc。我通过复制函数解决了这个问题。
【解决方案2】:

当您打开终端时,.bash_profile 被执行,因此PS1 被定义。然后你执行屏幕,屏幕读取环境变量PS1,其中包括对parse_git_branch的调用并尝试解析它。但是,由于 screen 没有执行 .bash_profile,所以函数 parse_git_branch 没有在 screen 内部定义。

PS1 的定义移动到.bashrc,因为screen 和iTerm 都会执行它。

【讨论】:

    【解决方案3】:

    这样简单多了,避免了不必要的sed:

    parse_git_branch () {
    
        while read -r branch; do
            [[ $branch = \** ]] && current_branch=${branch#* }
        done < <(git branch 2>/dev/null)
    
        [[ $current_branch ]] && printf ' [%s]' "$current_branch"
    
    }
    

    【讨论】:

      【解决方案4】:

      您的 sed 语句末尾缺少 '

      parse_git_branch() {
          git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
      }
      export PS1="[\W\$(parse_git_branch)]$ "
      

      另外,bash-3.2 似乎对我有用

      【讨论】:

      • 不幸的是它对我不起作用。我也必须在 screenrc 中添加一些东西吗?
      • 您是否仍然收到“找不到命令”消息?您的 .bash_profile 中还有什么?为了好玩,试着在你的 .bash_profile ``testFunc () { echo "test!" 中加入一个测试函数。 }`` 并调用它。
      • 我解决了。一旦我进入屏幕,我就会使用'source ~/.bash_profile'。它会恢复所有设置。感谢您的帮助。
      • 我需要在我的 mac 中运行这个和我的 .bashrc 文件,否则在重新启动后它们不会被应用。我会尝试将这些记录在某处...感谢每个人的贡献:)
      【解决方案5】:

      我在 OS X High Sierra 中切换到 root 或开始 ssh-agent /bin/bash 时遇到了同样的错误,我解决了将其放入 /etc/bashrc 并检查我是否是 root

      if [[ $UID == 0 ]]; then
              PS1="\[\e[1;31;40m\]\u@\h \W\[\e[0m\]\$ "
      else
              parse_git_branch() {
                      git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
              }
              PS1="\u@\h \[\033[32m\]\w\[\033[33m\]\$(parse_git_branch)\[\033[00m\] $ "
      fi
      

      【讨论】:

        猜你喜欢
        • 2019-09-06
        • 2018-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-19
        • 2010-10-23
        • 2017-07-31
        • 1970-01-01
        相关资源
        最近更新 更多