Pergunta

I am working on branch A and the feature/task is not done. Then I need to switch to another branch B for a quick fix. When I try to switch on another branch Git forces me to save my local changes otherwise I 'll lose my all local changes.

I need to commit my incomplete code. Is there any way that I can switch between multiple branches without committing and losing any code? Or is there a better way to handle the situation?

Foi útil?

Solução

One option, as mipadi demonstrates, is to simply use git stash.

Another option is to simply just commit your current work in progress, switch branches, and then when you're ready to switch back, do a mixed reset back to your previous commit:

# While working on "feature" branch,
# you suddenly need to go work on a hotfix:
$ git commit --all --message "Backup my feature work"
$ git checkout -b hotfix master

# You did your hotfix, and are ready to go back to feature
$ git checkout feature
$ git reset HEAD^

git reset HEAD^ will do a mixed reset back to the commit before you did a backup commit, and all of the changes you made in your backup commit will be restored to your working copy. From the official Linux Kernel documentation for git reset (emphasis mine):

Resets the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has not been updated. This is the default action.

Outras dicas

You can use git stash, which will save your changes without creating a commit.1

First, stash your changes:

$ git stash

Then switch to your other branch:

$ git checkout branch-B

When you're ready, go back to your original branch and unstash your changes:

$ git checkout branch-A
$ git stash pop

See the documentation linked above for more details and specifics on additional use cases.


1 Technically it does create a commit, but git stash uses some magic so you don't actually see the commit, and Git's tools know how to deal properly with these pseudo-commits.

I know this question is old, I just want to share one technique that could help you handle this situation. You can actually commit it to the branch and undo it later on.

1. Commit to the branch. (Commit only. Do not push.)

$ git commit --all --message "Commit Message here."

2. If you want to continue working on the branch, just checkout and undo your last commit without losing your latest changes.

$ git reset --soft HEAD~1

Note the --soft flag: this makes sure that the changes in undone revisions are preserved. After running the command, you'll find the changes as uncommitted local modifications in your working copy.

You can read more here.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top