Why are changes in one branch visible in another branch?

Roman picture Roman · Nov 24, 2017 · Viewed 7.2k times · Source

I execute the following sequence of commands:

git init rep
cd rep/
echo '111' > 1.txt
git add 1.txt 
git commit -m '1'
git checkout -b dev
echo '222' > 1.txt 
git checkout master
more 1.txt 

As a result of these commands I see

222

And I do not understand why. As you can see I create and go into the 'dev' branch. I do some changes there but I do not add and do not commit them. Why after going back from 'dev' to 'master' I do see the changes that I did in 'dev'? Shouldn't they stay in dev until I add, commit and merge them back to master?

Answer

Raman Sharma picture Raman Sharma · Nov 24, 2017

All the untracked files does not get impacted when you move in between different branches. As they belong to your filesystem and, GIT is unaware that to which branch these files belong. So when you commit those files, then GIT is aware of which files belong to which branch. And can remove or add files in working area based upon your branch.