I just faced a situation that seems illogical to me with Git. I have a repo with a plenty of commits, so at this stage it has only one branch (master).
Suppose this branch has a file called MyFile.txt. Now I need to create a different branch because I want to make some changes to a few files and I don't want to do it master branch directly, so I run:
git checkout iss53
Now the schema looks like this:
Fine, I have switched to branch iss53, I run ls -l
and the MyFile.txt. One of the changes include deleting the MyFile.txt file, so:
git rm MyFile.txt
Nice, running ls -l
again shows there's not MyFile.txt anymore. So I switch back to the master branch:
git checkout master
But… the MyFile.txt file has vanished as well. My logic says that if I deleted the file on a branch, it should be applied only to that branch, so why is the file deleted from the master branch as well? Note that I haven't made any commits yet, just branching.
Note: Both images are taken from Git-scm.
Best Answer
The answer is in your question :
If you don't commit, the changes are always kept in your working directory. Switching the branch doesn't affect your working directory, and the working directory also doesn't affect your last commit. You are seeing that the file is deleted, but the reality that it is deleted from your working directory only. If you want to clear the changes and return to the last commit use this command :
So the file will be restored again.
Maybe it is not logic for you, but this behavior can be useful. Imagine that you have 2 branches :
master
anddevelopment
, and you should always work ondevelopment
before you move the changes tomaster
. Let's say that you forgot to switch todevelopment
before starting working, then -before you commit- you realized that you are onmaster
. The solution is simple, just switch todevelopment
then commit.