章节 ▾ 第二版

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

在 Zsh 中使用 Git

Zsh 也自带用于 Git 的标签补全库。要使用它,只需在你的 .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 键来图形化地导航列表。这适用于 Git 命令、它们的参数和存储库内的东西的名称(如 refs 和 remotes),以及文件名和所有 Zsh 知道如何标签补全的其他东西。

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

除了 vcs_info 之外,你可能更喜欢 Git 自带的提示符定制脚本,称为 git-prompt.sh;有关详细信息,请参见 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