1
2

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 1 year has passed since last update.

[git]1コマンドで最新のブランチにチェックアウトするコマンド

Last updated at Posted at 2023-10-13

経緯

レビューの時など、
どうせ一番最新のブランチにチェックアウトするのに、わざわざブランチ名を入れてチェックアウトするのがすごく煩わしい。どうにかブランチ名を入力せずにブランチを切れる方法を探してた。

コマンド

git switch $(git for-each-ref --sort=-committerdate --format="%(refname:short)" refs/remotes/ | head -n 1 | sed 's#origin/##')

git switch ブランチの切り替え(checkoutでも良い)
for-each-ref: ブランチの取得
--sort=-comitterdate: 降順に並び替え
--format="%(refname:short)": ブランチ名だけを表示
refs/remotes/: 取得するブランチをリモートに限定
head -n 1: ブランチを一つだけ表示
sed 's#origin/##': 余計なorigin/を削除

あとは~/.gitconfigにエイリアスを設定して終了!

sed〜は無理矢理感あって微妙かも...

追記

git switch $(git for-each-ref --count=1 --sort=-committerdate --format="%(refname:short)" refs/remotes/ | sed 's#origin/##')

head -n 1よりも--count=1の方がスマートですね

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?