amindfv
amindfv

Reputation: 8448

Get git stash --patch to ignore changes I've already added

Is there a way to run git stash --patch in a way that only asks about unstaged changes?

From the docs, it looks like I should be able to do something like

git stash save --patch --keep-index

but that asks me about each change, even the ones I've already git added

In other words, if I do something like

echo "one" > a
echo "two" > b
git add .
git commit -m "foo"
echo "1" >> a
echo "2" >> b
git add a

how can I run git stash --patch so that I'm only asked about the change to file b?

Upvotes: 1

Views: 76

Answers (2)

janos
janos

Reputation: 124646

Reading through git stash --help, there's simply no option to do what you want, as of version 1.7.10.

The --keep-index is just about keeping the index. For example, let's start from this state:

$ date >> file1
$ date >> file2
$ git add file1
$ git status -s
M  file1
 M file2

If you do git stash --patch now and accept all changes, you'll get:

$ git status -s
MM file1

That is, the index is preserved (when using --patch, the --keep-index is automatically on). git stash undid the staged changes, but you can bring them back with git checkout file1, thanks to having preserved the index.

Now let's return to the state before the stash:

$ git stash pop
$ git checkout file1
$ git status -s
M  file1
 M file2

And let's stash again without keeping the index:

$ git stash --patch --no-keep-index
$ git status -s
$

No changes of any kind, no staging area, the index is gone.

So no, you cannot use git stash --patch to stash only unstaged changes. If you don't really need the select changes interactively, then you can git add changes you don't want to add, and then do git stash --keep-index (without --patch):

$ git status -s
M  file1
 M file2
$ git stash --keep-index
$ git status -s
M  file1

Notice the inconsistent behavior: there are no unstaged changes to file1 this time, unlike when we stashed with --patch.

Upvotes: 1

mockinterface
mockinterface

Reputation: 14860

It isn't possible, stash is always going to inspect your index. A stash is represented internally as two commits - one that records the work dir state and the second one records the state of the index, and they are children of the HEAD.

However if what you want is to put aside your unstaged changes, why don't you just run git diff > mypatchfile and later on git apply your patch file.

Upvotes: 0

Related Questions