On local branch, don't want to commit changes, but need to switch to another branch
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 reading, 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.
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.