[筆記] 如何讓 shell 顯示 git branch [powershell/bash]

Visits: 1

如何讓 shell 顯示 git branch

shell 是工程師每天的工作環境,每天的開發都會用 git 指令來進行軟體開發作業。專案一多,常常會忘記自己現在處於哪個 branch 上,每次都用 git branch 來顯示也很麻煩, google 了一下如何顯示現在的 git branch 在 shell 上,紀錄一下。

Windows Powershell

首先在終端機安裝 posh-gitoh-my-posh 套件

Install-Module posh-git -Scope CurrentUser
Install-Module oh-my-posh -Scope CurrentUser

安裝完成後,在終端機輸入 notepad $PROFILE ,會用 notepad 打開一個 powershell 的設定檔,在新增下列指令,就可以讓每次開啟 powershell 的時候都套用 theme.

Import-Module posh-git
Import-Module oh-my-posh
Set-PoshPrompt -Theme 

theme_name 可以用 Get-PoshThemes 查詢 或到這個網站查詢

我是選用 ys ,以下範例

file

Ubuntu shell

ubuntu 的 shell 設定檔放在 ~/.bashrc 這個位置,把第 59-64 行原生的 color_prompt 設定註解掉。

# THE SIX LINES BELOW are the default prompt and the unset (which were in the original .bashrc)
# if [ "$color_prompt" = yes ]; then
#     PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
# else
#     PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
# fi
# unset color_prompt force_color_prompt

然後新增下面這段指令即可。

# parse git branch
parse_git_branch() {
 git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
if [ "$color_prompt" = yes ]; then
 PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[01;31m\] $(parse_git_branch)\[\033[00m\]\$ '
else
 PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(parse_git_branch)\$ '
fi

下圖左為全預設的情形,把 ~/.bashrc 修改並重開 shell 後的情形如下圖右,如果當前目錄為 git 追蹤目錄的話,就顯示紅色的 branch name 。

file

收工~

source: ask ubuntu

About the Author

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

You may also like these