When working on a project, you might be half-way through a feature branch change when a bug is raised against master. You're not ready to commit your code, but you also don't want to lose your changes. This is where git stash
comes in handy.
Run git status
on a branch to show your uncommitted changes:
(master) $ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: business/com/test/core/actions/Photo.c
no changes added to commit (use "git add" and/or "git commit -a")
Then run git stash
to save these changes to a stack:
(master) $ git stash
Saved working directory and index state WIP on master:
2f2a6e1 Merge pull request #1 from test/test-branch
HEAD is now at 2f2a6e1 Merge pull request #1 from test/test-branch
If you have added files to your working directory these can be stashed as well. You just need to stage them first.
(master) $ git stash
Saved working directory and index state WIP on master:
(master) $ git status
On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
NewPhoto.c
nothing added to commit but untracked files present (use "git add" to track)
(master) $ git stage NewPhoto.c
(master) $ git stash
Saved working directory and index state WIP on master:
(master) $ git status
On branch master
nothing to commit, working tree clean
(master) $
Your working directory is now clean of any changes you made. You can see this by re-running git status
:
(master) $ git status
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working directory clean
To apply the very last stash, run git stash apply
(additionally, you can apply and remove the last stashed changed with git stash pop
):
(master) $ git stash apply
On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: business/com/test/core/actions/Photo.c
no changes added to commit (use "git add" and/or "git commit -a")
Note, however, that stashing does not remember the branch you were working on. In the above examples, the user was stashing on master. If they switch to the dev branch, dev, and run git stash apply
the last stash is put on the dev branch.
(master) $ git checkout -b dev
Switched to a new branch 'dev'
(dev) $ git stash apply
On branch dev
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: business/com/test/core/actions/Photo.c
no changes added to commit (use "git add" and/or "git commit -a")