章节 ▾ 第二版

A1.7 附录 A:Git 在其他环境 - Zsh 中的 Git

Zsh 中的 Git

Zsh 也自带一个用于 Git 的 Tab 补全库。要使用它,只需在你的 .zshrc 中运行 autoload -Uz compinit && compinit。Zsh 的界面比 Bash 更强大一些。

$ git che<tab>
check-attr        -- display gitattributes information
check-ref-format  -- ensure that a reference name is well formed
checkout          -- checkout branch or paths to working tree
checkout-index    -- copy files from index to working directory
cherry            -- find commits not merged upstream
cherry-pick       -- apply changes introduced by some existing commits

模糊的 Tab 补全不仅仅是列出;它们有有用的描述,你可以通过重复按 Tab 键图形化地导航列表。这适用于 Git 命令、它们的参数、仓库内部事物的名称(如 refs 和 remotes),以及文件名和所有其他 Zsh 知道如何 Tab 补全的内容。

Zsh 自带一个用于从版本控制系统获取信息的框架,名为 vcs_info。要在提示符的右侧包含分支名称,请将以下行添加到你的 ~/.zshrc 文件中

autoload -Uz vcs_info
precmd_vcs_info() { vcs_info }
precmd_functions+=( precmd_vcs_info )
setopt prompt_subst
RPROMPT='${vcs_info_msg_0_}'
# PROMPT='${vcs_info_msg_0_}%# '
zstyle ':vcs_info:git:*' formats '%b'

这会在你的 shell 位于 Git 仓库中时,在终端窗口的右侧显示当前分支。当然,左侧也受支持;只需取消 PROMPT 赋值的注释即可。它看起来有点像这样

Customized `zsh` prompt
图 185. 自定义 zsh 提示符

有关 vcs_info 的更多信息,请查看其在 zshcontrib(1) 手册页中的文档,或在线访问 https://zsh.sourceforge.io/Doc/Release/User-Contributions.html#Version-Control-Information

你可以选择使用 Git 自带的提示符自定义脚本 git-prompt.sh,而不是 vcs_info;详情请参阅 https://github.com/git/git/blob/master/contrib/completion/git-prompt.shgit-prompt.sh 兼容 Bash 和 Zsh。

Zsh 功能强大,甚至有专门的框架来改进它。其中一个名为“oh-my-zsh”,可在 https://github.com/ohmyzsh/ohmyzsh 找到。oh-my-zsh 的插件系统带有强大的 Git Tab 补全功能,并拥有各种提示符“主题”,其中许多主题会显示版本控制数据。oh-my-zsh 主题的一个示例只是使用此系统可以实现的一个例子。

An example of an oh-my-zsh theme
图 186. oh-my-zsh 主题的一个示例
scroll-to-top