Translate

2013年10月10日木曜日

プロンプトに現在のgitローカルリポジトリ/ブランチを表示する

作業中に現在見ているgitローカルリポジトリの場所とブランチ、それからコミット状況がテキスト色で分かると便利だなー、と思い、その辺りをスクリプトにまとめてみた。

cat ~/bin/gitbranch.bash
#!/bin/bash
# echo git branch for color PS1

name=`git symbolic-ref HEAD 2> /dev/null`
if [[ -z $name ]]
then
        exit
fi

name=`basename $name`
st=`git status`
repos=`git remote -v | \
grep -o '\/.*' | \
sed -e "s/[ \s\/]//g" | \
sed -e "s/(fetch)//g" | \
sed -e "s/\.git//g" | \
awk "NR==1{print}"`
if [[ -n `echo $st | grep "nothing to commit"` ]]
then
    color="\[\e[32;1m\]"
else
    color="\[\e[31;1m\]"
fi
reset_color="\[\e[0m\]"
echo -E $color[$repos $name]$reset_color
これを.bashrcあたりで読み込んでPS1にセットしておくと、プロンプトが常に更新される感じになる。
PS1="\$(~/bin/gitbranch.bash)\n[\u@\h: \W]> "
プロンプトそのものはこんな感じ。
[Repo-Name branch]
[username@localhost: dir] > # commit前 [Repo-Name branch]
[username@localhost: dir] > # commit後