2014年8月8日 星期五

抓取 Git branch 資訊

之前有一篇「Linux 提示字元」裡有提到,可以寫 function 來取得一些 git 的資訊,然後加進提示字元裡面。
我是由這個網站得到的:http://ihower.tw/blog/archives/5436
該網站中是由這兩個 function 來取得 branch name 以及 commit time 的資訊。

function git_branch {
    ref=$(git symbolic-ref HEAD 2> /dev/null) || return;
    echo "("${ref#refs/heads/}") ";
}

function git_since_last_commit {
    now=`date +%s`;
    last_commit=$(git log --pretty=format:%at -1 2> /dev/null) || return;
    seconds_since_last_commit=$((now-last_commit));
    minutes_since_last_commit=$((seconds_since_last_commit/60));
    hours_since_last_commit=$((minutes_since_last_commit/60));
    minutes_since_last_commit=$((minutes_since_last_commit%60));

    echo "${hours_since_last_commit}h${minutes_since_last_commit}m ";
}

這兩個的 function 重點在於 git symbolic-ref HEAD 及 git log --pretty=format:%at -1 兩個指令。不過我想查 git --help 就會有了,我暫時還沒查。

倒是 echo "("${ref#refs/heads/}") "; 這個讓我覺得蠻有趣的,一時也沒找到資料。
靠實驗得到,它可以把 "#" 之後的字串拿掉。但這字串只能從最前頭開始。
例如我把它改成 echo "("${ref#heads/}") "; 這樣的話,什麼事也不會發生。
(有在 git 下的話,ref 應該會是 "refs/heads/<branch_name>")

沒有留言:

張貼留言