LoginSignup
47
22

More than 1 year has passed since last update.

git初学者が必ず出会う「error: Your local changes to the following files would be overwritten by checkout:」について

Last updated at Posted at 2022-09-04

どうもaono1234と申します。記事がいいなと思ったらtwitterのフォローもお待ちしております‼
https://twitter.com/takeshi_program

今回は初心者が必ず遭遇するerror: Your local changes to the following files would be overwritten by checkout:のエラーについて説明したいと思います。

gitをまだ触って日が浅い方は100%このエラー文を経験するかと思います。
私も経験しました。🤢

このエラーはどのような場合に出力されるのか?書いていきます。

はじめに

本記事は以下の読者様が対象です。

  • プログラミング初心者

  • gitを少し触ったことがある人

  • add commitしたことある人

先に結論(⭕下に図解があります)

【パターンA】該当のエラーが発生するケース

  1. burach Aから新しいbranch Bを切る
  2. branch Bにてなんでも良いのでコードをcommit する。
  3. branch Bにて なんでも良いので2で変更をcommitしたファイルについて「ワーキングツリー上でコードを変更する」or「変更したコードを git add する」。(commitしない)
  4. burach Aに移動する
  5. エラー発生

【パターンB】該当のエラーが発生しないケース👈重要!!😲

  1. burach Aから新しいbranch Bを切る
  2. branch Bにてなんでも良いのでコードをcommit する。
  3. branch Bにてなんでも良いので「ワークツリー上でコードを変更する」or「変更したコードを git add する」。(commitしない)
  4. burach Aに移動する
  5. エラー発生しない

実演

【パターンA】該当のエラーが発生するケース

current_branch[master]
    $ git checkout -b test
        #Switched to a new branch 'test'

#【このタイミングでindex.htmlのコードを一部変更】
current_branch[test]
    $ git add .

current_branch[test]
    $ git status
        #On branch test
        #Changes to be committed:
        #  (use "git restore --staged <file>..." to unstage)
        #    new file:   index.html ←ステージングしたファイル

current_branch[test]
    $ git commit -m "first commit"
        #[test a0d22ab] first commit
        # 1 file changed, 1 insertion(+)


#【このタイミングでindex.htmlのコードを一部変更】
current_branch[test]
    $ git add .

current_branch[test]
    $ git switch master
        #error: Your local changes to the following files would be overwritten by checkout:
        #        index.html
        #Please commit your changes or stash them before you switch branches.
        #Aborting

【パターンB】該当のエラーが発生しないケース

current_branch[master]
    $ git checkout -b test
        #Switched to a new branch 'test'

#【このタイミングでindex.htmlのコードを一部変更】
current_branch[test]
    $ git add .

current_branch[test]
    $ git status
        #On branch test
        #Changes to be committed:
        #  (use "git restore --staged <file>..." to unstage)
        #    new file:   index.html ←ステージングしたファイル

current_branch[test]
    $ git switch -
        #M       index.html
        #Switched to branch 'master'

図解

【パターンA】はエラーが発生するのに対して、【パターンB】はエラーが発生しません。
これはワークツリーとステージングエリアは同時期のブランチには並行移動できるが、過去のブランチには移動できないことを意味しています。以下のようなイメージです。

【パターンA】

パターンA.PNG

【パターンB】

パターンB.PNG

おわりに

如何でしょうか?
イメージは掴めましたか?

この違いを把握しておけば
master ブランチで間違って作業していた!😨
という場合でも、testブランチがまだコミットしてない(並行移動できる位置)であれば
ワークツリーとステージングエリアをtestブランチにそのまま引っ越しすることができますね😄

これからも色々と記事を投稿したいと思っておりますので、
どうぞ、よろしくお願いします! :smiley:

47
22
1

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
47
22