Skip to content
abhikp edited this page Aug 3, 2011 · 2 revisions

Say that you're working on a feature and you have several uncommited changes. Along comes a frantic PM telling you to switch gears and fix a mission critical bug. You look at your changes and realize they're not commit worthy. This gives you two options: say you're in the middle of something or use git stash.

  1. Let's create three changes and stage one of them.

    % echo "I'm going to stash this" >> README
    % echo "I'm going to stash this" >> INSTALL
    % git add INSTALL
    % echo "I'm going to stash this too" >> INSTALL
    

    Running git status should show us that we have some changes

    # On branch master
    # Changes to be committed:
    #   (use "git reset HEAD <file>..." to unstage)
    #
    #   modified:   INSTALL
    #
    # Changed but not updated:
    #   (use "git add <file>..." to update what will be committed)
    #   (use "git checkout -- <file>..." to discard changes in working
    #   directory)
    #
    #   modified:   INSTALL
    #   modified:   README
    #
    
  2. To stash these changes run git stash.

    % git stash
    Saved working directory and index state WIP on master: 94ae280 Adding clean instructions to INSTALL
    HEAD is now at 94ae280 Adding clean instructions to INSTALL
    % git status
    # On branch master
    nothing to commit (working directory clean)
    
  3. Let's create and check in the "bug fix".

    % echo "Bug fix." >> README
    % git commit -am "Fixing the bug."
    
  4. Now pop the changes (the pop will not work if you have uncommitted changes).

    % git stash pop
    Auto-merging README
    CONFLICT (content): Merge conflict in README
    % git status
    # On branch master
    # Your branch is ahead of 'origin/master' by 1 commit.
    #
    # Changes to be committed:
    #   (use "git reset HEAD <file>..." to unstage)
    #
    #   modified:   INSTALL
    #
    # Unmerged paths:
    #   (use "git reset HEAD <file>..." to unstage)
    #   (use "git add/rm <file>..." as appropriate to mark resolution)
    #
    #   both modified:      README
    #
    

    Since the stash included changes on README and we commited a change on README, a conflict arose. You can resolve it via your favorite merge tool.

    % cat README
    Hey this a test for git. Welcome, to git.
    <<<<<<< Updated upstream
    Bug fix.
    =======
    I'm going to stash this
    >>>>>>> Stashed changes
    

    Also notice that the pop did not preserve the changes to INSTALL that were staged and unstaged. All changes to a file will be combined and left unstaged (in this case they were staged, not sure why).

Clone this wiki locally