git - 损坏的 bash 提示符换行

标签 git bash prompt

我在 OsX 上自定义我的 bash 提示符以包括 git 分支和分支状态的一些标记。这打破了换行。

我知道I have to add \[ and \] to prevent this issue , 但在函数中这样做确实会乱七八糟地显示\[ 和\]。

我该怎么做才能在这些函数中转义此类序列?

免责声明:这是我第一次尝试编写 bash 脚本。

function parse_git_dirty {
  # TODO make git status response a variable
  # [branch+] : working dir has staged changes
  if [[ $(git status 2> /dev/null | grep "to be committed") ]]
  then S=$S"$(tput setaf 2)+$(tput sgr0)"
  fi
  # [branch+] : working dir has unstaged changes
  if [[ $(git status 2> /dev/null | grep "not staged for commit") ]]
  then S=$S"$(tput setaf 1)+$(tput sgr0)"
  fi
  # [branch+] : working dir has untracked files
  if [[ $(git status 2> /dev/null | grep "tracked files") ]]
  then S=$S"$(tput setaf 1)+$(tput sgr0)"
  fi
  # [branch<] : local branch is behind origin
  if [[ $(git status 2> /dev/null | grep "Your branch is behind") ]]
  then S=$S"$(tput setaf 5)<$(tput sgr0)"
  fi
  # [branch>] : local branch is ahead origin
  if [[ $(git status 2> /dev/null | grep "branch is ahead of") ]]
  then S=$S"$(tput setaf 5)>$(tput sgr0)"
  fi
  # [branch<>] : branches have diverged
  if [[ $(git status 2> /dev/null | grep "have diverged") ]]
  then S=$S"$(tput setaf 5)<>$(tput sgr0)"
  fi
  echo $S
}
function parse_git_branch {
  git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'
}
function show_git_branch {
  if [[ $(parse_git_branch) ]]
  then echo "$(tput setaf 2)($(tput sgr0)$(parse_git_branch)$(parse_git_dirty)$(tput setaf 2))$(tput sgr0)"
  fi
}
export PS1="\u\[$(tput setaf 2)\]@\[$(tput sgr0)\]\h\[$(tput setaf 2)\]:\[$(tput sgr0)\]\W\[\$(show_git_branch)\] "

最佳答案

我很高兴听到您已经解决了您的版本的问题,但我认为可能值得指出的是,git 已经分发了一个有用且经过深思熟虑的 bash 函数,称为 __git_ps1您可以将其包含在您的 PS1 中。例如,您可以这样使用它:

 export PS1='blah blah blah$(__git_ps1 " (%s)") '

如果您不在 git 存储库中,$(__git_ps1 "(%s)") 将变成空字符串。但是,如果您是,则将使用格式字符串。这通常会显示您当前的分支,但如果您正在进行 merge 或 rebase ,则会显示。

默认情况下,__git_ps1 不会显示树是否脏了或是否有未跟踪的文件,因为在某些存储库中,这可能会使 bash 提示出现的速度慢得令人恼火。但是,如果您也想查看此信息,则将 GIT_PS1_SHOWDIRTYSTATEGIT_PS1_SHOWUNTRACKEDFILES 设置为非空值,它就会显示这些信息。

您可以在 git-completion.sh source file 顶部找到更多信息.

关于git - 损坏的 bash 提示符换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5050377/

相关文章:

bash - 为什么 bash 有时不将 python 程序的输出刷新到文件中

git - 理解 git commit --only 和 pre-commit 钩子(Hook)

git - 为什么没有 git 版本目录?

linux - 为什么无法在函数中获取shell脚本的参数计数

bash - 在 bash 提示符下倒退

mysql - 是否可以用颜色设置 MYSQL_PS1 而不会弄乱提示行宽度计算?

batch-file - 使用命令提示符复制文件夹并重命名

git - git filter-branch 遇到问题, "ambiguous argument"

git - 如何将分支的一部分 rebase 到主分支?

linux - 如何在 shell 脚本中使用 line 作为可选函数?