Stashing in Git

testYourselfGit Git447 1 0

Stashing in Git is useful when you started to working on some changes in the project, but you have not finished them and you do not want to commit them. Stashing takes the dirty state of your working directory and saves it on a stack of unfinished changes that you can reapply at any time.

List the stash

The git stash list command lists the stash entries that you currently have. Each stash entry is listed with its name, the name of the branch that was current when the entry was made, and a short description of the commit the entry was based on.

$ git stash list
stash@{0}: On master: added products page
stash@{1}: On master: added contact page
stash@{2}: On master: added home page

Add entries to a stash

To add some changes to stash just run git stash push.

The git stash push saves your local modifications to a new stash entry and reverts the working directory to match the HEAD commit. You can also use the shorter command git stash as it is a shorthand to the git stash push.

$ git stash push -m "added products page"
Saved working directory and index state On master: added products page

Pop entry from a stash

To get your changes back run git stash pop command. This command remove a single stashed state from the stash list and apply it to your working directory.

The git stash apply command works like the git stash pop but it doesn't remove the state from the stash list.

$ git stash pop
On branch master
Your branch is ahead of 'origin/master' by 1 commit.

Creating a branch from a stash

You can also use the git stash branch comand that creates a new branch for you, checks out the commit you were on when you stashed your work, reapplies your work there, and then drops the stash if it applies successfully.

$ git stash branch products-page
Switched to a new branch 'products-page'

Displaying a stash

The git stash show command display the changes recorded in the stash entry as a diff between the stashed contents and the commit back when the stash entry was first created.

git stash show -p stash@{1}

Remove a stash

The git stash drop command remove a single stash entry from the list of stash entries. When no argument is provided, it removes the latest one.

$ git stash drop stash@{1}
Dropped stash@{1} (be6208e83f2eece1d535d08ba7829e704059223c)

Remove all stashes

The git stash clear remove all the stash entries. Please note that you may not be able to recover deleted entries after you run this command.

$ git stash clear