December 19, 2022

Git Stash: deep dive

git-stash is a powerful subcommand in Git, that stores changes in a hidden place. Staged or unstaged changes or untracked files are stashed in a stash stack and the working directory is reverted to the last commit.

It is useful when changes made to a branch is not ready to be commited and there is a need to switch to another branch.

error: Your local changes to the following files would be overwritten by checkout:
Please commit your changes or stash them before your switch branches.

Stash is local to the Git repository and not pushed to remote repository.

Stashing changes

git stash stores uncommited changes in a stash stack and revert to the last commit. The command enables to perform other git operations and apply the stash at a later point. Note that git stash push is equivalent to git stash and also git stash save is now a deprecated command.

Optional message can be added to distinguish different stash.

git stash push -m "optional message"

By default, git does not stash untracked files. But untracked files can be stashed by using the -u flag or the --include-untracked option. Furthermore, ignored files can be included using the -a or --all option when running git stash

Stash apply and stash pop

Once a stash has been stored, it can be retrieved two ways: git stash apply and git stash pop. The two commands differs slightly.

git stash apply - apply changes and leave a copy in the stash.

git stash pop - apply changes and remove the files from the stash.

Listing entries

More than one stash can be stored and can be viewed through a list. Each stash has an entry in the list with its name.

git stash list

stash is in the following format:


The number in curly braces is the index of that stash.

Stash show

This command outputs the diff between the stashed contents and the last commit when the stash were created.

git stash show

Removing entries

git stash drop remove a single entry from the list of stash entries while git stash clear will remove all the stash entries.

Partial stashes

Individual changes can stashed using the patch flag.

git stash --patch

Branching off a stash

Create a new branch your apply the stashed changes to, and then pop the changes onto it.

git stash branch <branch-name> stash@{stash-index}

Recovering a deleted stash

A stash is a just another commit in the repository and a deleted stash is an orphaned commit.

git-fsck helps finding dangling objects, that is, checking for orphaned commits which can be applied.

Flag --lost-found writes the dangling objects into .git/lost-found/commit or .git/lost-found/other/, depending on type.

git fsck --lost-found
ls -1 .git/lost-found/commit/ | xargs -n 1 git log -n 1 --pretty=oneline 
git stash apply [id]



Powered by Hugo & Kiss.