Search code examples
gitgit-commitgit-checkoutgit-stash

On local branch, don't want to commit changes, but need to switch to another branch


I am working on branch branch-A and the feature/task is not done yet. Then I need to switch to another branch branch-B for a quick fix. When I try to switch on another branch Git forces me to save my local changes otherwise I will 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?


Solution

  • 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.