Stashing changes in Git

stash command takes changes in working tree and staging area away and store them on a stack. You can reapply the changes later.

Stash changes

# Stashes changes in working tree and staging area away 
$ git stash

# Stash changes in working tree and index, and keep staged changes in index
$ git stash --keep-index

# Stash changes, also include untracked files
$ git stash --include-untracked

# Stash changes, also include untracked and ignored files
$ git stash --all

To stash only changes in specified files or folder, run below command:

# Stash only changes in pathspec
$ git stash -- <pathspec>

# Examples:
# Stash only changes in inc/menu.php
$ git stash -- inc/menu.php

List all stashes

# List the stashes that have been made on the curren branch 
$ git stash list
stash@{0}: WIP on master: b1f092d update: hello.php

The above result shows the stash name, the branch name, and the commit this stash was based on.

Reapply stashed changes

# Apply the top stash on the stack
$ git stash apply

Use stash@{n} to reference the n stash from the top on the stack, it is started from 0 :

# Apply the top stash on the stack
$ git stash apply stash@{0}

# Apply the stash before stash@{0} on the stack
$ git stash apply stash@{1}

Be aware that the staged changes in the stash are not restaged. To do that, run:

# Revert working tree and staging area
$ git stash apply --index

The reapplied stash is not removed from the stack. To remove a stash, use drop command:

# Remove the top stash on the stack
$ git stash drop stash@{0}

To reapply a stash and remove it from stack in one command, use pop command:

# Repplay a stash and remove it from stack
$ git stash pop stash@{0}

Note:

You do not have to be on the same branch to apply the changes. There will be merge conflicts if there is change can not be applied cleanly.

Show content of a stash

# Show content of the top stash
$ git stash show stash@{0}

# Show cnotent of the second recent stash in patch form
$ git stash show -p stash@{1}

Clear all stashes

# Remove all stashes in the stack
$ git stash clear

Note: The stashes removed may be impossible to recover.