0
1

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 checkout 時に origin が要る/要らない問題

Posted at

初めに

  • Gitをチーム開発で1年ほど使用
  • コマンド操作には慣れてきたが、git checkout 時に origin を書く必要がある場合とそうでない場合があり、動作の違いを明確に理解できていなかったため調査しました。

概要

Gitではリモートブランチを操作する際に、

git checkout origin/hotfix/feature-x

と書く場合と、

git checkout hotfix/feature-x

とする場合があり、後者だけ成功することがあります。

この違いがなぜ生まれるのか、Gitの内部動作を踏まえて整理しました。


1. git checkout hotfix/feature-x の場合

ローカルにそのブランチが存在しないとき、Gitは以下のように動作します。

リモート追跡ブランチ origin/hotfix/feature-x が存在する場合、Gitは自動的にローカルブランチを作成し、追跡ブランチとして設定してくれます。

git fetch origin
git checkout hotfix/feature-x

これは裏で以下のような動作をしてくれているのと同じになります。

git checkout -b hotfix/feature-x origin/hotfix/feature-x

出力例:

branch 'hotfix/feature-x' set up to track 'origin/hotfix/feature-x'.
Switched to a new branch 'hotfix/feature-x'

2. git checkout origin/hotfix/feature-x の場合

一方、こちらの書き方は別の意味になります。

git checkout origin/hotfix/feature-x

これはリモート追跡ブランチをそのままチェックアウトするという意味であり、編集・コミットができません。

いわば「読み取り専用モード」でのブランチ切り替えです。

また、以下のようなミスも発生しやすいです。

git checkout origin hotfix/feature-x
# ❌ エラー:Gitは "origin" というリモートと "hotfix/..." を同時に扱えない

3. よく使う正しい書き方まとめ

✅ ローカルブランチをリモートから新しく作る場合

git checkout -b hotfix/feature-x origin/hotfix/feature-x

✅ Git 2.23 以降の場合(switch 推奨)

git switch -c hotfix/feature-x --track origin/hotfix/feature-x

4. なぜPushの origin と混同しやすいのか?

Gitではよく以下のようなPushコマンドを使います。

git push origin hotfix/feature-x

これは:

「このブランチを origin って名前のリモートリポジトリに送ってね!」という意味

一方、以下のような checkout の使い方をしようとすると混同しやすくなります。

git checkout origin/hotfix/feature-x

これは:

「originリモートにあるブランチを一時的に読み取り専用で見るね!」


🎯 例えるなら:

  • git push origin ブランチ名
    → 「データ送るから受け取ってね、origin先生!

  • git checkout origin/ブランチ名
    → 「origin先生のところにあるメモだけ見せて

  • git checkout origin ブランチ名
    → 「originって人とブランチ名って人を同時に呼び出す」謎コマンド

    Git「えっ、何?どこ見ればいいの?わかんない…(爆死\(^o^)/)」


まとめ

  • git checkout ブランチ名 はローカルにブランチがなければ origin/ブランチ名 を自動で探して作ってくれる
  • git checkout origin/ブランチ名 は読み取り専用で、基本的には作業には不向き
  • git push origin ブランチ名 のような書き方と混同しやすいが、用途が異なる
  • git checkout origin ブランチ名 のような構文は完全にNG(構文ミス)
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?