Drew LeSueur
Drew LeSueur

Reputation: 20145

Git: Check out a branch keeping uncommitted changes

In Git, how would I check out an older branch while preserving all my changes from the current branch, but they would just be marked as uncommitted changes or new files.

Is there a command like git checkout-but-keep-changes branch_name?

Upvotes: 9

Views: 8864

Answers (2)

George Hilliard
George Hilliard

Reputation: 15942

Git normally does this when you check files out, assuming the changes you have made are not to files that are going to be changed by the checkout. For example, suppose I have the following files in a repository:

a.txt
b.txt
c.txt

Now I'll make a change to file a.txt:

a.txt (modified)
b.txt
c.txt

Now suppose I have two other branches, a-changed and b-changed, in which a.txt and b.txt have been modified, respectively.

If I try to check out b-changed, Git will do that without complaint, because my working directory changes don't conflict with the changes made on that branch. However, if I try to check out a-changed, Git won't do that, because I have changes made to my local copy, and the checkout would clobber them. Git says:

$ git checkout a-changed
error: Your local changes to the following files would be overwritten by checkout:
        a.txt
Please, commit your changes or stash them before you can switch branches.
Aborting

Git does provide you with a way to get around this problem: stash your changes! This saves your current changes as a patch and undoes them in the working directory. That is, after running git stash, the working directory will be cleaned, and your changes placed onto the stash stack. You can then checkout the desired branch and run git stash pop, which will pop your changes off the stack and apply them to the new working tree. Hopefully, they'll apply cleanly. If they don't, you'll get the standard merge conflict markers in a.txt. Notably, the stash is not popped off the stack, so you need to do a git stash drop after you resolve the merge.

You can also pass the -m (--merge) flag to the checkout command, which indicates that you would like your changes to be three-way merged with the incoming changes. Generally, I prefer stashing things.

Upvotes: 11

Drew LeSueur
Drew LeSueur

Reputation: 20145

I was looking for a git reset --soft

Sorry my question wasn't very clear.

Upvotes: 0

Related Questions