Removing a file in a branch in git implies removing it from the master branch as well

branchgit

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).

Master branch

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:

New branch

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 :

Note that I haven't made any commits yet, just branching.

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 :

git reset --hard HEAD

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 and development, and you should always work on development before you move the changes to master. Let's say that you forgot to switch to development before starting working, then -before you commit- you realized that you are on master. The solution is simple, just switch to development then commit.

Related Question