【问题标题】:Basic bash script for terminal prompt终端提示的基本 bash 脚本
【发布时间】:2012-02-17 19:51:23
【问题描述】:

目前我的终端提示包含git信息。

示例清理目录:michaelespinosa:~/Sites/example.com [git:master]
脏目录示例:michaelespinosa:~/Sites/example.com [git:master*]

我还想为 git 信息着色(如果干净则为绿色,如果脏了则为红色)。

我想我可以添加一个函数 (parse_git_color) 并根据是否存在星号使用 if else 语句相应地设置它的颜色。

问题在于,无论是干净目录还是脏目录,它都会一直返回绿色。我认为问题与 if 语句 parse_git_dirty == "*" 将 parse_git_dirty 的值与 "*" 进行比较有关。

function parse_git_dirty {
  [[ $(git status 2> /dev/null | tail -n1) != "nothing to commit (working directory clean)" ]] && echo "*"
}
function parse_git_color {
  if [ parse_git_dirty == "*" ]; then
    echo '\033[0;31m\'
  else
    echo '\033[0;32m\'
  fi
}
function parse_git_branch {
  git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e "s/* \(.*\)/$(parse_git_color)[git:\1$(parse_git_dirty)]/"
}

感谢任何帮助! 谢谢

【问题讨论】:

    标签: bash shell terminal


    【解决方案1】:

    请注意 PS1 中的\$(...)。它是重要的,因为只有 \$() 每次打印提示时都会调用您的命令。 $() 只被调用一次(在 PS1 初始化时)。

    function parse_git_dirty
    {
      [[ "$(git status 2> /dev/null | tail -n1)" != "nothing to commit (working directory clean)" ]] && echo "*"
    }
    
    function parse_git_color
    {
      if [ "$(parse_git_dirty)" == "*" ] ; then
        echo "0;31m"
      else
        echo "0;32m"
      fi
    }
    
    function parse_git_branch
    {
      git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e "s/* \(.*\)/[git:\1$(parse_git_dirty)]/"
    }
    
    export PS1="\[\033[\$(parse_git_color)\]\$(parse_git_branch) \[\033[0m\]"
    

    【讨论】:

    • 我更新了您的建议,但没有奏效。我最终得到了 michaelespinosa:~/Sites/example.com 033[0;32m[git:master]。我认为问题与 if 语句有关,因为无论如何它都会返回 else。
    • @michaelespinosa 对不起,我没有测试我的建议。我修正了我的答案。
    • 感谢@sgibb,关键是将 parse_git_dirty 更改为 "$(parse_git_dirty)"
    • 随着 git 状态消息的变化,这会中断。确保将parse_git_dirty!= 之后的比较与干净存储库的默认消息相匹配。例如,1.8.2 对干净的存储库有不同的消息,parse_git_dirty 将始终返回 "*"
    猜你喜欢
    • 2011-05-10
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    • 2011-01-11
    相关资源
    最近更新 更多