Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch between Git branches removing files in another branch

Ok, when I switch between branches, and delete a file from one branch it is carried over into the other.

I created a new repo, and pushed to a remote with a file "README.md".

I then switch to a feature branch git checkout -b feature/hello and add a file hello.md. I add this file git add hello.md and commit git commit -m "hello added". I then push this branch and everything is great! git push origin feature/hello.

Now I want to switch branch to do some work, and on this feature branch we are going to remove hello.md and add a new file goodbye.md.

  • git checkout -b feature/goodbye
  • rm hello.md
  • git checkout feature/hello

Now in the feature/hello branch I have the files README.md goodbye.md.

Why does deleting files in one branch remove them from another?

like image 700
WishIHadThreeGuns Avatar asked Oct 15 '25 04:10

WishIHadThreeGuns


1 Answers

TL;DR - changes are local, until you commit them.

The file hasn't been removed from the "branch" per se, but rather, its only been removed locally.

When you do rm [filename], you are only removing the file locally. This is different from git rm [filename]. Some more details in this post.

If you check the code you pushed, the file would still be there. In fact, the file is still in the branch -- at least a far as git is concerned, since you haven't committed the deletion as a change yet. Its only when you git add [filename] that git would record the file as deleted. (In fact, even then, you can still change branches and git commit the file as deleted in a different branch!)

This is just the way git works. You can make changes locally and move between different branches, and then commit the changes to a branch of your choice. (Of course, you may encounter some conflicts along the way, but in principle this works).

In fact, its actually really useful. Say, you are in branch foo and you've just made some changes to a few files. But, what you actually wanted to do was make those changes in a new branch bar which you forgot to create & checkout. Since the changes are still local, you can simply git checkout -b bar and commit the changes in branch bar as you originally intended.

By the way, this post talks about ways to get the deleted file back, in case the rm was a mistake.

like image 96
costaparas Avatar answered Oct 17 '25 17:10

costaparas