bash - 用于终端提示的基本 bash 脚本

标签 bash shell terminal

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

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

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

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

问题在于,无论是干净目录还是脏目录,它都会一直返回绿色。我相信这个问题与比较 parse_git_dirty 的值与“*”的 if 语句 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)]/"
}

任何帮助表示赞赏!
谢谢

最佳答案

请注意 \$(...)在 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\]"

关于bash - 用于终端提示的基本 bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9334473/

相关文章:

不在目录中时的 Git 标记状态

python - 输入与 raw_input : Python Interactive Shell Application?

terminal - 禁用 WGET 历史记录跟踪

用于查看原始文件的 Linux 命令,包括其分隔符

cmd - PhpStorm - 以管理员身份运行终端(cmd)

bash - bash 中的 printf : "09" and "08" are invalid numbers, "07"和 "06"都很好

bash - ansible:远程机器上的文件是否有类似 with_fileglobs 的东西?

android - 在多个模拟器上运行 Android 应用程序的雄心勃勃的尝试 - 无法停止模拟器

linux - 删除包含符号链接(symbolic link)的文件夹

linux - 如何在 Linux shell 脚本中提示是/否/取消输入?