LoginSignup
103
79

More than 5 years have passed since last update.

get current branch name

Last updated at Posted at 2012-12-26

現在のブランチ名を文字列として取り出す方法いろいろ。
正直よく理解していない部分も多いので、間違いなどあればご指摘いただけると嬉しいです。

git-symbolic-refを使う

branch名の取得なら、多分これが一番良い? HEADを指定することで現在のワーキングツリーがどのブランチかを得ることができる。
zshのVCS_INFO_git_getbranchでもこれが使われている模様。

$ git symbolic-ref --short HEAD

--shortオプションはv1.7.10以降から?
https://github.com/git/git/blob/master/Documentation/RelNotes/1.7.10.txt#L125


git-name-rev, git-describeを使う

git-name-revは指定したrevに対するsymbolic name(?)を返すので、HEADを指定することで現在の最新コミットに関連するbranch名やtag名を得ることができる。

$ git name-rev --name-only HEAD

git-describeは指定したrevに最も近いtagなどを取得することができるようで、--allオプションを指定すればbranch名も対象になり、取得することができる。

$ git describe --all

どちらもbranch名だけでなくtag名も対象になるので純粋にbranch名だけを取り出したい場合はさらにフィルタリングが必要になるかも。


git-branchの出力を加工する

git branch -aですべてのブランチが表示され、current branchには行先頭に"*"がつくのでその行からブランチ名を取り出して使うことができる。

$ git branch -a | grep -E '^\*' | cut -b 3-
$ git branch -a | grep -E '^\*' | sed -e 's/^\* //'


git-statusの出力を加工する

git status --short --branch --untracked-files=noでもcurrent branch名が取れるのでそれを加工することでも取得できる。

$ git status -sbu no | cut -b 4-


参考URL

103
79
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
103
79