How to discard unstaged changes in a file with a branch name?

git checkout -- path/to/file

To discard unstaged changes in a file which has the same name as a branch name use git checkout -- path/to/file.

When trying to discard unstaged changes where the file and the branch have the same names, a simple git checkout will fail.

In this case you need to add the -- after checkout for argument disambiguation.

Layer 1
Terminal Example
git branch -v
* main        b2626e9 Adding file with branch name
  test-branch 120f7ab Adding tests

git status
On branch main
Changes not staged for commit:
  (use "git add ..." to update what will be committed)
  (use "git restore ..." to discard changes in working directory)
    modified:   test-branch

no changes added to commit (use "git add" and/or "git commit -a")

git checkout test-branch
error: Your local changes to the following files would be overwritten by checkout:
  test-branch
Please commit your changes or stash them before you switch branches.
Aborting

git checkout -- test-branch

git status
On branch main
nothing to commit, working tree clean

See git checkout to learn more about it.

Last modified on November 30, 2021.