how to do an export for git stash


April 2019


820 time


I want to export one stash (the changes) that I see in my stash list in a .zip/.gz file. I have found the following command:

git stash show -p > patch

which saves the changes in a file, but I also want to keep .png files, etc... I am looking for a way to compress all of the changes contained in the stash in a file or a folder. Do you know any solution ?

2 answers


While Samual Robert's answer does solve the stated problem, something to note:

git stash show will combine all staged and unstaged changes into a single patch, and will exclude untracked files even if you used git stash -u. By default git apply will make all of the changes in the patch into unstaged changes; you can make them staged by giving the --index option. But to preserve the distinction between staged and unstaged changes, or to include untracked files that are in the stash, you need to do something else.

A stash internally consists of two or three commits and some ref manipulation, so one option is to generate a patch from each commit and then reconstruct the stash manually on the other end. It takes a little trickery to get the right patches because of the way the commits are related.

git show stash^2 --binary >index.patch
git show stash^3 --binary >untracked.patch
git diff --binary stash^2 stash >wip.patch

Then on the receiving end

git apply index.patch
git add .
git apply wip.patch
git apply untracked.patch

Now the uncommitted state has been recreated on the other repo, and if you want you could re-stash it there.

If you need to materialize the change on the receiving end directly as a stash, without going through your worktree and index -- e.g. because the receiving side isn't in a "clean" state - you could do it using bundles. But there is a trick to making this work. On the source repo

git bundle create stash.bundle stash^..stash

On the receiving repo

git remote add bundle stash.bundle
git fetch stash:temp
git update-ref --create-reflog refs/stash temp
git branch -D temp

Note that we had to give an explicit refspec to get the stash ref out of the bundle. If we'd mapped it directly to refs/stash, then we can't count on a reflog entry being created - and without the reflog entry, it's not a usable stash. So instead we brought it in to a temporary branch, then used update-ref to create (or move) the stash ref and update the reflog.


Try it with --binary option to export

git stash show -p --binary > changes.patch

When you want to import it, apply the patch

git apply changes.patch