Keep ignored files when switching branches in git

1.6k Views Asked by At

Eclipse has it's own files .project, .classpath and .settings folder. In git, I have them in the .gitignore file, because I don't want them to be tracked in the remote repository. My problem is that when I switch branch, and then switch back, those files have been removed, so eclipse doesn't recognize the project and I have to import it again so they're generated.

Is there a way to tell git to ignore those files, but keep them in the local repo or something so I don't loose them when switching branches, but changes to them are not tracked and they're not pushed to the remote either?

Files are shown when running git ls-files -o.

I've checked GIT: How to keep ignored files when switching branches?, but the file still appears when doing git status.

EDIT:

git status alone shows this:

$ git status
On branch refactorizacion
Your branch is up-to-date with 'origin/refactorizacion'.

nothing to commit, working directory clean

This doesn't work:

$ git add -f .project
$ git rm --cached .project

I've also tried this, but file appears after git status:

$ git add -f .project
$ git update-index --assume-unchanged .project
$ git status
On branch refactorizacion
Your branch is up-to-date with 'origin/refactorizacion'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .project
1

There are 1 best solutions below

6
On

The second one will obviously not work. You are adding a file to index, but without committing, it does not know which previous version to compare with. So git status will show it as a new file. You can only apply update-index after you have committed it once.

In the first case, I am not sure why you would add a file before removing it.

As mentioned in the question you have referred to, you should simply remove the file (if git is still tracking it) and add it to .gitignore, so that git does not track it anymore. This will insulate it from branch switching.

EDIT: Make sure that the file was removed using git rm <file> and that the commit in which this was added is present in all branches. Then add the file to gitignore.