# shell 實現自動顯示 git branch
## 作者說:
我今天認知到了`~/.bashrc`其實就是一shell腳本,怎麼改都可以。
今天應該要是充滿生產力的一天,不過都拿來研究這東西了 \_.w_.
## `~/.bashrc`
1. 自動顯示 git branch
我的實現只覆蓋了 `cd` 以及 `git checkout*`
```
# 修改後 + Git branch (顯示完整路徑)
function parse_git_branch {
git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
# 監聽
PROMPT_COMMAND='
{
if [[ $BASH_COMMAND =~ "git checkout"* ]]; then
update_git_branch > /dev/null 2>&1
fi
} > /dev/null 2>&1'
# 在每次 cd 操作後更新分支名稱
function update_git_branch {
if [[ -z $(parse_git_branch) ]]; then # not in .git dir?
# remove old one
PS1="${PS1//$bashrcBranchSave/}"
else # in .git dir?
if [[ $PS1 == *"${bashrcBranchSave}"* ]]; then # old one exist?
#find old and replace with new
PS1=${PS1//$bashrcBranchSave/$(parse_git_branch)}
#echo "T1"
else # old one non-exists ?
# add it
PS1=${PS1//'\[\033[01;32m\]$'/$(parse_git_branch)'\[\033[01;32m\]$'}
#echo "T2"
fi
# save the old one
bashrcBranchSave=$(parse_git_branch)
fi
}
# 每次進入新目錄時自動更新分支
cd() {
builtin cd "$@" && update_git_branch
}
```
在`~/.bashrc`預設有這一段,我稍微修改了一下。
```
if [ "$color_prompt" = yes ]; then
#origin
#PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
# only full dir and no $
PS1=' \[\033[01;34m\]\w\[\033[00m\] '
PS1stack=$PS1
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
;;
*)
;;
esac
# add git branch to PS1
PS1="${PS1}$(parse_git_branch)\[\033[01;32m\]$ \[\033[00m\]"
```
## 結果

## 紀錄:舊版本
```
# 在每次 cd 操作後更新分支名稱
function update_git_branch {
PS1="${PS1stack}$(parse_git_branch)\[\033[01;32m\]$ \[\033[00m\]"
}
```
這樣實做的問題是,無法與其他需要更改PS1的套件兼容,新版本長很多,但能夠兼容。例如: venv。