Skip to content

Instantly share code, notes, and snippets.

@jioo
Last active March 13, 2024 14:59
Show Gist options
  • Star 43 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jioo/eebe4c39d800baf99c0db703ded4842c to your computer and use it in GitHub Desktop.
Save jioo/eebe4c39d800baf99c0db703ded4842c to your computer and use it in GitHub Desktop.
How to export stash as a file, and apply it to another computer

Stash current changes

  • git > Stash > Stash (Include Untracked)

Create stash as patch

git stash show "stash@{0}" -p > changes.patch

Apply patch

git apply changes.patch
@ryanesrapado
Copy link

@jioo I need to export also in the same file untracked files that were stashed along with the tracked ones, can you help me with this, I can show them with
git show stash@{0}^3
But I do not know how to include them along the tracked and stashed ones

@ryanesrapado
Copy link

@jioo
Got it, just in case this help:
1- Save staged changes without include untracked changes
git --no-pager stash show stash@{1} -p > patch_1
2- Save staged changes only untracked changes
git diff 4b825dc642cb6eb9a060e54bf8d69288fbee4904 stash@{1}^3 >> patch_1(diff against an empty tree object)
3- Apply staged save in patch_1 fixing trailing whitespaces
git apply --reject --whitespace=fix patch_1

Alternative for step 2 recommended in case git changes its hash algorithm:
git diff $(git hash-object -t tree /dev/null) stash@{1}^3 >> patch_1

Explanation:
4b825dc642cb6eb9a060e54bf8d69288fbee4904 -> Git always has an empty tree in every repository whose ID is the magic number 4b825dc642cb6eb9a060e54bf8d69288fbee4904
stash@{1}^3 -> Untracked Files that were staged
printf "tree 0\0" | sha1sum
git hash-object -t tree /dev/null
git diff $(printf "tree 0\0" | sha1sum | awk '{print $1}') stash@{1}^3 >> patch_1

Source:
https://ericbouchut.com/2021/07/22/git-stash-internals/
https://ah.thameera.com/4b825dc642cb6eb9a060e54bf8d69288fbee4904/

git apply --reject --whitespace=fix patch_1
--whitespace=fix ensures whitespace errors are fixed before path is applied
--reject ensures atomicity (so no working directory files are modified if patch will not apply)

Source:
https://git-scm.com/docs/git-apply(check out for *.rej files with --reject param)

@LouDnl
Copy link

LouDnl commented Aug 17, 2023

@ ryanesrapado

git config stash.showIncludeUntracked true

https://git-scm.com/docs/git-stash#_configuration

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment