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

多分脳死で使っているgit branch -M を解説

1
Posted at

はじめに

Gitでブランチ名を変更する際に使うgit branch -Mコマンド
-Mオプションの意味を正確に理解していますか?

この記事では、git branch -Mの挙動とを簡単に説明します。

git branch -M の基本

git branch -M main

このコマンドは、現在のブランチ名を強制的に変更します。

  • -M = --move --forceの短縮形
  • 既存のブランチを上書きしてでもリネームする

具体例で理解する

# 現在のブランチ構成
* master
  main (既に存在)

# -m を使った場合(安全)
git branch -m main
# エラー: fatal: A branch named 'main' already exists.

# -M を使った場合(強制)
git branch -M main
# 成功:既存の main ブランチを上書き

実際の使用例

パターン1:master → main への変更(一般的)

git branch -M main
git push -u origin main

GitHubなどのデフォルトブランチ名の変更に対応するための操作です。
最初にgitレポジトリを作る際によくやる操作ですね

image.png

パターン2:現在のブランチ以外を変更

# feature ブランチを新しい名前に変更
git branch -M feature new-feature-name

パターン3:typoを修正

# 間違った名前のブランチを修正
git branch -M fetaure feature  # typo修正

注意点

1. 強制上書きのリスク

繰り返しになりますが-Mは既存ブランチを確認なしで上書きします。

# 危険な例
git branch -M important-branch
# もし important-branch が既に存在していたら、その内容は失われる

推奨される使い分け

-m を使うべき場合

  • 通常のブランチ名変更
  • 誤操作を防ぎたい場合
git branch -m new-branch-name

-M を使うべき場合

  • 確実に上書きしたい場合
  • プロジェクト初期でmaster → main のような標準的な変更
git branch -M main

まとめ

  • -m:安全なブランチ名変更(同名が存在したらエラー)
  • -M:強制的なブランチ名変更(同名が存在しても上書き)
  • master → main の変更では-Mがよく使われる
  • リモートへの反映は別途git pushが必要

参考

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