80

I have a git repository. It has A B C D E ... commits. Now I want to checkout D as a new branch named Dbranch. So I excute:git checkout D -b Dbranch. And now I want to delete this branch. Firstly I need to switch to master branch , and then use git branch -d Dbranch to delete it. But when I excute git checkout master, it gives me the error.

error: The following untracked working tree files would be overwritten by checkout:
    source/a/foo.c
        ...... (too many lines)
Please move or remove them before you can switch branches.
Aborting

How to delete the Dbranch?

Fei Xue
  • 1,655
  • 4
  • 16
  • 26
  • Related post - [.gitignore and “The following untracked working tree files would be overwritten by checkout”](https://stackoverflow.com/q/4858047/465053) – RBT Nov 30 '19 at 07:46

3 Answers3

207

Try git checkout -f master.

-f or --force

Source: https://www.kernel.org/pub/software/scm/git/docs/git-checkout.html

When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes.

When checking out paths from the index, do not fail upon unmerged entries; instead, unmerged entries are ignored.

Benjamin W.
  • 33,075
  • 16
  • 78
  • 86
dekdev
  • 4,835
  • 2
  • 25
  • 32
  • 3
    Ahh my life saved! I was so nervous seeing that all my existing files were removed after switching the branch. After forced checkout I have get back all my items. – itsazzad Mar 03 '15 at 06:32
  • 1
    I was having a problem where I was getting the "untracked working tree files" error but `git status -u` was displaying nothing...I had no idea how to delete this mysterious untracked file, but this command helped me circumvent that for now – jlewkovich Nov 13 '15 at 17:31
24

With Git 2.23 (August 2019), that would be, using git switch -f:

git switch -f master

That avoids the confusion with git checkout (which deals with files or branches).

And that will proceeds, even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
If --recurse-submodules is specified, submodule content is also restored to match the switching target.
This is used to throw away local changes.

VonC
  • 1,042,979
  • 435
  • 3,649
  • 4,283
-1

do a :

git branch

if git show you something like :

* (no branch)
master
Dbranch

You have a "detached HEAD". If you have modify some files on this branch you, commit them, then return to master with

git checkout master 

Now you should be able to delete the Dbranch.

Mali
  • 2,754
  • 14
  • 18