Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git allows for branch change with unstaged changes

Git is allowing me to change branches when I have changes not staged for commit (modified files).

Is there a configuration for this somewhere?

Edit: At first I thought this was a configuration that I needed to set to disallow changing between branches if there are modified unstaged files. But by Emily's comment, it appears that you're prompted if the files differ between branches, and not prompted otherwise.

like image 305
Dave Avatar asked Dec 15 '11 20:12

Dave


People also ask

Can I change branch with uncommitted changes?

You may switch branches with uncommitted changes in the work-tree if and only if said switching does not require clobbering those changes.

What does unstaged mean in git?

Unstaged changes are changes that are not tracked by the Git. For example, if you copy a file or modify the file. Git maintains a staging area(also known as index) to track changes that go in your next commit.


1 Answers

How it decides

A quick experiment shows the following.

Suppose you're on branch dev and you've modified foo.txt. Without committing, you try to check out master. One of two things will happen.

  1. If foo.txt was modified in master in a commit that dev doesn't have, you won't be allowed to switch without committing, because master has a "new" version of the file that conflicts with the unstaged changes.

    To "check out" master, therefore, would require Git to update foo.txt to the newer version that master has, destroying your unstaged changes. To prevent your losing work, it won't change branches.

  2. Otherwise, the modification has been done "since" the version master knows about, and you'll be able to change branches. Git doesn't have to update the file because master has no new information about the file.

For the "whoops" changes

Because of the above, if you have unstaged changes in files on one branch and realize you actually want to commit the changes on another, you may or may not be able to check out the other branch.

You can, however, do the following:

  • git stash save "here's a summary of my changes" (summary will show up in git stash list)
  • git checkout otherbranch
  • git stash pop (which is a combination of git stash apply and git stash drop)
like image 53
Nathan Long Avatar answered Oct 21 '22 21:10

Nathan Long