Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not switch git branch: "Untracked file" but working directory clean

Tags:

git

I want to switch the branch. but get the error

error: Untracked working tree file 'foo.phtml' would be overwritten by merge.

If I delete this file the next file is complained about. The problem is that there is a very vast difference of files in the two branches.

This is what I tried:

$ git reset --hard HEAD
HEAD is now at 8a2a95c Initial checkin
$ git checkout otherbranch
error: Untracked working tree file 'foo.phtml' would be overwritten by merge.
$ git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 1 and 677 different commit(s) each, respectively.
#
nothing to commit (working directory clean)

What is wrong here?

I also already tried

git clean -f -d
like image 418
Alex Avatar asked Nov 21 '12 17:11

Alex


People also ask

Can I switch branch with untracked files?

Take away: changing branches does not touch/change/remove untracked or checked in files. Remember that the working directory and index are not 'cleared' before the branch content is loaded into it!

Does git clean remove untracked files?

Remember that 'git clean' only removes untracked files. To find out if a file is tracked or not, developers can issue the 'git status' command from within the repository. The git clean command will only delete certain files.


2 Answers

You face the problem that the branch you want to check out contains numerous files like foo.phtml which are not tracked in your current branch. It seems that you can just delete the files, so try:

git checkout -f otherbranch
like image 79
mavam Avatar answered Oct 24 '22 08:10

mavam


Just in case you do care about the files later, use

git stash -u

that will clean your working directory but in case you lose something, you can get it back from the stash. Now you can go ahead and checkout your other branch.

The other scenario is that the files are ignored in one branch and not in the other. In this case you should follow up the stash command (if git status shows something is changed) with the git checkout -f theotherbranch.

like image 29
Adam Dymitruk Avatar answered Oct 24 '22 07:10

Adam Dymitruk