git will see the file as untracked because it is not committed yet. You have to commit the change before you switch branches.
So you created a branch and made changes to that branch. When you try to switch back to master
git will disallow this, because there are changes that are not committed yet (or explicitly ignored; (that is actually what the untracked
means)
The reason the file is restored when you force checkout (git checkout -f master
) master
is because the file is in master
If you want to do this you will have to do the following
Create and check out branch
git checkout -b somebranch
Remove the file from somebranch
(--cached
will actually remove the file from the index, but will leave the file intact on your filesystem. See git-rm reference docs)
git rm --cached somefile
Commit the change
git commit -m "Remove somefile"
This will remove the file from git, but not from disk, so now to git you have an untracked change (somefile is on disk but not in git)
If you want other contributors to be able to checkout the branch, link it to a remote
git push --set-upstream origin somebranch
Now the file is removed from origin/somebranch
and not master
When you add a file to .gitignore
it is not removed from the repo if it is already committed. Changes to the file, howeve, will be ignored (so also deleting it). If you do that you still have to remove the file and commit. After that git will not track the file anymore when recreated (or any other action on the file).