0

I created a new local repo with 1 file in it.

+ foo
|- .git
|- foo.txt (4 bytes)

I now modify foo.txt and stage my change. Afterwards I execute git checkout -b new-branch. Shouldn't my new branch have the state and files of the upstream-branch before my temporary changes?

Here is an example:

#-------setup git repo with 1 file and foo.txt (4 bytes)-------
$ git init .                  
Initialized empty Git repository in foo/.git/
$ echo 1234 > foo.txt
$ git add .
$ git commit -m 'first message'
[master (root-commit) 4aa4409] first message
1 file changed, 1 insertion(+)
create mode 100644 foo.txt

#-------modify foo.txt, stage and create new branch-------
$ echo 123456789 > foo.txt
$ git stage foo.txt 
$ git checkout -b new-branch
Switched to a new branch 'new-branch'
$ cat foo.txt
123456789     #<---- I expected 1234 here
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Daniel Stephens
  • 2,371
  • 8
  • 34
  • 86
  • 1
    Run git status and it'll happily tell you that change is still staged. I'm not sure what you're asking, because your experiment tells you exactly what happens. – jonrsharpe Dec 25 '19 at 17:28
  • Also see [Move existing, uncommitted work to a new branch in Git](https://stackoverflow.com/q/1394797/112968) which explains this expected behavior – knittl Dec 25 '19 at 17:57

2 Answers2

2

git-checkout documentation says "Local modifications to the files in the working tree are kept, so that they can be committed to the ." So, the observed behavior is the expected behavior.

Digging a bit deeper, there are two cases with git-checkout.

  1. If the branch X that is being checked out does not have the changed file or has changed file with the same content as the current branch Y, then git retains local changes to the file (allowing the changes to be committed to branch X).
  2. If not, then git will complains that your local changes will be overwritten.

Your situation is the first case and, hence, the local changes are retained.

1

Nope... as long as the changes are not committed (in other words, as long as they are not added yet or in index), if you try to checkout another branch, git will try to bring them along with you. It's not a bug, it's intended.

eftshift0
  • 26,375
  • 3
  • 36
  • 60