Reputation: 451
If I create a new branch from master, then make some changes, if I don't commit the changes and then checkout master, my changes follow me back to master. I don't get it... If I commit the changes in the new branch and then checkout master, then master remains unchanged. Isn't this a recipe for making unwanted changes in master? What is the proper workflow here?
git init
echo something > newfile
git add newfile
git commit -a -m "first commit"
git checkout -b dev
echo $(date) >> newfile
git checkout master
[user@toolbox test]$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: newfile
no changes added to commit (use "git add" and/or "git commit -a")
[user@toolbox test]$ cat newfile
something
Thu 26 Sep 2019 09:00:49 PM GMT
[user@toolbox test]$
But...
[user@toolbox test]$ git checkout -- newfile
[user@toolbox test]$ git checkout dev
Switched to branch 'dev'
[user@toolbox test]$ git commit -a -m "I dont get this"
On branch dev
nothing to commit, working tree clean
[user@toolbox test]$ git checkout master
Switched to branch 'master'
[user@toolbox test]$ git status
On branch master
nothing to commit, working tree clean
[user@toolbox test]$ cat newfile
something
[user@toolbox test]$
I was expecting that "checkout" just switches branches. But obviously there is something I don't understand about the git workflow.
Upvotes: 0
Views: 483
Reputation: 30317
The trick here is to understand that what you have on your files on the working tree, if you try to checkout another branch, git will see if the modified file is the same (without your uncommitted changes) where you want to go and in HEAD revision.... if it is the same then git understands that the switch you are asking to do is not a problem... your working tree changes (and the new files) will accompany you on the switch. If, however, the modified file is not the same between HEAD and where you want to go, git will refuse to checkout (unless you force, of course). So, all in all, git is trying to follow your commands to the best it can and keeping you from (unwillingly) busting your work (particularly what hasn't been committed yet). Now.... having said that, what part of the process you described makes you scratch your head? Is it the git checkout -- newfile
part? Because it's just the way you ask git to set a file the way it is on HEAD revision (in other words, disregard the changes I made on this file and set it the way it was before I edited it.... it can even be used to set the content of the file the way it is on another branch/tag/revision.... and in that case you would get the file into the index waiting to be committed).
Upvotes: 3