2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

デフォルトブランチを取得する

Last updated at Posted at 2020-08-27

はじめに

これまでgitのデフォルトブランチはmasterというのが常識でしたが、
2020年10月1日以降に新規作成したGitHubリポジトリではデフォルトブランチにmainが指定されるようになります。

Set the default branch for newly-created repositories
https://github.blog/changelog/2020-08-26-set-the-default-branch-for-newly-created-repositories/

これからgitを扱う再利用可能なスクリプトを書く際には、リポジトリのデフォルトブランチがmasterなのかmainなのか知りたくなる場面があるかと思います。

方法

GitLabのCI_DEFAULT_BRANCHのような変数が予め用意されている場合はそれを使えば十分ですが、
そうでない環境では何らかの手段でデフォルトブランチを調べることになります。

gitとsedが使える環境では、以下のコマンドを実行するとデフォルトブランチがわかります。

$ git symbolic-ref refs/remotes/origin/HEAD | sed 's@^refs/remotes/origin/@@'
master

別解として、cutとrevを使うと次のようにかけます。

$ git symbolic-ref refs/remotes/origin/HEAD | rev | cut -d/ -f1 | rev
master
$ git symbolic-ref refs/remotes/origin/HEAD | cut -d/ -f4
master

もっといいやり方があったら教えて下さい。

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?