将parse_git_branch函数从bash转换为zsh(用于提示)

Dan*_*ark 7 git bash zsh

我在Bash中使用此功能

function parse_git_branch {
  git_status="$(git status 2> /dev/null)"
  pattern="^# On branch ([^${IFS}]*)"
  if [[ ! ${git_status}} =~ "working directory clean" ]]; then
    state="*"
  fi
  # add an else if or two here if you want to get more specific

  if [[ ${git_status} =~ ${pattern} ]]; then
    branch=${BASH_REMATCH[1]}
    echo "(${branch}${state})"
  fi
}
Run Code Online (Sandbox Code Playgroud)

但我决定使用zsh.虽然我可以在我的.zshrc中完美地使用它作为shell脚本(即使没有shebang),但错误是此行上的解析错误if [[ ! ${git_status}}...

我需要做些什么才能为zshell做好准备?

编辑:我得到的"实际错误"是" parse error near }指带有奇怪双重的行}},它对Bash有效.

编辑:这是最终的代码,只是为了好玩:

parse_git_branch() {
    git_status="$(git status 2> /dev/null)"
pattern="^# On branch ([^[:space:]]*)"
    if [[ ! ${git_status} =~ "working directory clean" ]]; then
        state="*"
    fi
    if [[ ${git_status} =~ ${pattern} ]]; then
      branch=${match[1]}
      echo "(${branch}${state})"
    fi
}

setopt PROMPT_SUBST
PROMPT='$PR_GREEN%n@$PR_GREEN%m%u$PR_NO_COLOR:$PR_BLUE%2c$PR_NO_COLOR%(!.#.$)'
RPROMPT='$PR_GREEN$(parse_git_branch)$PR_NO_COLOR'
Run Code Online (Sandbox Code Playgroud)

感谢大家的耐心和帮助.

编辑:最好的答案是我们所有人:git status瓷器(UI).好的脚本与GIT管道相悖.这是最后的功能:

# The latest version of Chris' function below

PROMPT='$PR_GREEN%n@$PR_GREEN%m%u$PR_NO_COLOR:$PR_BLUE%2c$PR_NO_COLOR%(!.#.$)'
RPROMPT='$PR_GREEN$(parse_git_branch)$PR_NO_COLOR'
Run Code Online (Sandbox Code Playgroud)

请注意,只有提示符是特定于zsh的.在Bash中,这将是你的提示加"\$(parse_git_branch)".

这可能会更慢(更多的GIT调用,但这是一个经验问题)但它不会被GIT的变化打破(它们不会改变管道).这对于一个好的脚本来说非常重要.

Chr*_*sen 5

你应该使用Git"plumbing"命令来提取你想要的信息."瓷器"命令(例如git status)的输出可能随时间而变化,但"管道"命令的行为更加稳定.

使用瓷器接口,它也可以在没有"bashisms"或"zshisms"(即=~匹配运算符)的情况下完成:

parse_git_branch() {
    in_wd="$(git rev-parse --is-inside-work-tree 2>/dev/null)" || return
    test "$in_wd" = true || return
    state=''
    git update-index --refresh -q >/dev/null # avoid false positives with diff-index
    if git rev-parse --verify HEAD >/dev/null 2>&1; then
        git diff-index HEAD --quiet 2>/dev/null || state='*'
    else
        state='#'
    fi
    (
        d="$(git rev-parse --show-cdup)" &&
        cd "$d" &&
        test -z "$(git ls-files --others --exclude-standard .)"
    ) >/dev/null 2>&1 || state="${state}+"
    branch="$(git symbolic-ref HEAD 2>/dev/null)"
    test -z "$branch" && branch='<detached-HEAD>'
    echo "${branch#refs/heads/}${state}"
}
Run Code Online (Sandbox Code Playgroud)

将输出集成到提示符中仍然是特定于shell的(即转义或引用$(对于bashzsh)并设置PROMPT_SUBST(对于zsh)).