できない.dev

Git で「Your local changes would be overwritten by checkout」でブランチを切り替えられない

未コミットの変更が切替先と衝突すると checkout が中断する仕様。
stash か commit で退避するか、捨ててよいなら restore してから切り替える。

公開: 更新:

症状できない · exit 1
git switch feature
error: Your local changes to the following files would be overwritten by checkout:
	note.txt
Please commit your changes or stash them before you switch branches.
Aborting
解決後できた · exit 0
git switch feature
Switched to branch 'feature'

2026-09-02 に alpine/git(Git 2.54.0) で実際に打って取った出力。検証環境の詳細

要約

error: Your local changes to the following files would be overwritten by checkout は、作業ツリーに未コミットの変更があり、切り替え先のブランチでは同じファイルが異なる内容になっているときに出る。

Git は変更を黙って上書きしないよう、切り替え自体を中断して保護してくれる。
退避(stash / commit)するか、捨ててよいなら破棄してから切り替えれば通る。

実行例

未コミットの変更を抱えたまま git switch を実行すると、上書きされるファイル名が並んだうえで中断され、終了コードは 1 になる。
git stash で変更を退避してから切り替え、git stash pop で戻すと、切替先のブランチに編集内容がそのまま残る。

$ git status --short
M note.txt
$ git switch feature
error: Your local changes to the following files would be overwritten by checkout:
	note.txt
Please commit your changes or stash them before you switch branches.
Aborting
$ echo $?
1
$ git stash
Saved working directory and index state WIP on master: a3a1b71 init
$ git switch feature
Switched to branch 'feature'
$ echo $?
0
$ git stash pop
Auto-merging note.txt
On branch feature
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
	modified:   note.txt
 
no changes added to commit (use "git add" and/or "git commit -a")
Dropped refs/stash@{0} (27ac7047053f0706a70f987803f3049d6a10f120)
$ echo $?
0
$ git branch --show-current
feature
$ cat note.txt
WORKING
line2
FEATURE

— 2026-09-02 時点の出力

検証環境Git 2.54.0 / 2026-09-02 検証
検証日
実行環境
alpine/git Alpine Linux v3.24
バージョン
  • Git 2.54.0

この記事の「実行例」は、上記の環境で実際にコマンドを実行して得られた出力をそのまま掲載しています。 再現手順はリポジトリの検証スクリプトとして管理し、定期的に再実行して出力を更新しています。

解決策

1. 変更を stash で退避する

git stash
git switch feature
git stash pop

切り替えの前に stash で作業を退避すれば、切り替え後に git stash pop で戻せる。
衝突したら通常のコンフリクト解決と同じ手順になる。

2. 変更を確定させる

git add -A
git commit -m "WIP"
git switch feature

残す価値のある変更なら commit してから切り替える。
ブランチを間違えても、後から git cherry-pick や git reset で移動できる。

3. 変更を破棄する

git restore .
# 特定ファイルだけなら
git restore path/to/file

要らない変更なら git restore で作業ツリーを HEAD の状態に戻す。
破棄すると元に戻せないので、消える内容を git diff で確認してから実行する。

4. 追跡すべきでないファイルを外す

echo "dist/" >> .gitignore
git rm -r --cached dist

生成物や環境依存ファイルが原因なら、.gitignore に加えて追跡から外す。
以降はブランチを切り替えても衝突しなくなる。

よくある原因

  1. 未コミットの衝突: 編集中のファイルが、切替先ブランチでは別内容になっている。
  2. 退避なしの切替: stash も commit もせずに git switch / git checkout <branch> を実行した。
  3. 追跡すべきでないファイル: node_modules やビルド生成物を追跡してしまい、ブランチ間で毎回ぶつかる。

この手順で直った?