Git
章節 ▾ 第二版

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 附帶的提示符號自訂腳本,而不是使用 vcs_info,該腳本稱為 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