Skip to content

Instantly share code, notes, and snippets.

@bobpaul
Created August 10, 2021 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bobpaul/bded251b8637061e6a7094e6141ef38f to your computer and use it in GitHub Desktop.
Save bobpaul/bded251b8637061e6a7094e6141ef38f to your computer and use it in GitHub Desktop.
`git stash --keep-index` includes changes that are on the index
###
# It is suggested to use the `--keep-index` option when using `git stash` if you don't want to stash
# changes already added to the index.
# This almost works as it leaves the index in the working tree untouched, but it includes the index tree in the patch that's stashed.
###
(>'o')>$ git init
^('o')^$ touch a
<('o'<)$ git add a
^('o')^$ git commit -am "initial commit"
[main (root-commit) 372d94c] initial commit
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 a
###
# Initial commit created with an empty file `a`
###
(>'o')>$ echo "Foo
>
> bar
>
> baz" > a
^('o')^$ git add a
###
# File is populated and changes added to the index
###
<('.'<)$ sed 's/Foo//' -i a
^('.')^$ git diff
diff --git a/a b/a
index b5d6cbf..e6b3d90 100644
--- a/a
+++ b/a
@@ -1,4 +1,4 @@
-Foo
+
bar
###
# File is changed more and diff shows how the file differs from the index (line `Foo` replaced with blank line)
###
(>'.')>$ git stash --keep-index
Saved working directory and index state WIP on main: 372d94c initial commit
^('.')^$ git stash list --patch
stash@{0}: WIP on main: 372d94c initial commit
diff --git a/a b/a
index e69de29..e6b3d90 100644
--- a/a
+++ b/a
@@ -0,0 +1,5 @@
+
+
+bar
+
+baz
###
# Unexpectedly, the stash contains the entire file a (all changes on the index as well as the changes in the working directory
# Desired behavior is that the stashed patch should match the `git diff` up above.
###
git commit -a "added bar and baz"
fatal: paths 'added bar and baz ...' with -a does not make sense
(>'.')>$ git commit -am "added bar and baz"
[main dc3b472] added bar and baz
1 file changed, 5 insertions(+)
^('.')^$ git stash pop
Auto-merging a
CONFLICT (content): Merge conflict in a
The stash entry is kept in case you need it again.
<('.'<)$ git diff
diff --cc a
index b5d6cbf,e6b3d90..0000000
--- a/a
+++ b/a
@@@ -1,4 -1,4 +1,8 @@@
++<<<<<<< Updated upstream
+Foo
++=======
+
++>>>>>>> Stashed changes
bar
^('.')^$
###
# Because the stash includes more than the diff, it pops uncleanly
###
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment