Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git branching and committing -- can you explain the theory behind this puzzling (to me) behavior?

Tags:

git

git-branch

I have a master branch and everything is fine in it. Then I create a branch called experimental and I create a new file. While in my experimental branch I add this file using the git add command. Then I checkout my master branch. While in my master branch I run git status and discover that this file has also been added to my master branch. I then run git commit -m "message" while in my master branch and the commit happens. Then I switch to my experimental branch and run git status and discover that the file has also been committed in my experimental branch.

Here is what I would have expected: Upon switching to the master branch after adding the new file I would expect that the file would not appear there. After all, I did not create the file while in the master branch and I did not add the file while in the master branch. So when I switch to the master branch and run git status why does it find the file already added and ready to commit? And when I then do commit it while in the master branch, why do I also find it committed in the experimental branch when I switch back? Did it commit to two branches at once?

like image 350
Deonomo Avatar asked Feb 22 '23 22:02

Deonomo


1 Answers

When you run git add, the file is not committed, it's only added to Git's "index". You probably wanted to run git commit after doing git add on your experimental branch.

When you switch branches in Git, the changes in your working directory and in the index are carried over as long as they don't conflict with any other files that change during the branch switch.

To address your specific concern:

...and discover that this file has also been added to my master branch.

If you haven't run git commit, then the file has not yet been added to any branch at all.

like image 58
Greg Hewgill Avatar answered Apr 19 '23 22:04

Greg Hewgill