gitでブランチ一覧を付番表示して一瞬で切り替えるエイリアス


ブランチ一覧表示から数字選ぶだけでブランチ切り替えできるようになるエイリアスを紹介します。ブランチ名を都度コピペして消耗してましたが、一気に捗るようになりました。

Mac・Linuxを想定しております。bashの場合は以下を~/.bash_profileに追記してsource ~/.bash_profileで更新するだけです。

~/.bash_profileの場合
function b() {
  command git branch --sort=-committerdate | cut -c 3- | head -n20 | cat -n
  command read -p "Enter Branch Number: " BranchNumber
  command git checkout $(git branch --sort=-committerdate | cut -c 3- | head -n20 |awk NR==$BranchNumber)
}

zshの場合は以下を~/.zshrcに追記してsource ~/.zshrcで更新です。

~/.zshrcの場合
function b() {
  command git branch --sort=-committerdate | cut -c 3- | head -n20 | cat -n
  read 'BranchNumber?Enter Branch Number: '
  command git checkout $(git branch --sort=-committerdate | cut -c 3- | head -n20 |awk NR==$BranchNumber)
}

コマンドは短くbの一文字を割り当てています。全てネイティブコマンドで動作してますので、カスタマイズも容易かと思います。全てのエンジニアに良いgitライフを!