Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stash only unstaged changes with git (not --keep-index)

Tags:

git

First of all, I do know about --keep-index. This is not what I want because it still stashes all changes, but leaves the staged one in the worktree. I would like to only stash the unstaged files, if possible without adding all changes again with git stash --patch.

like image 476
iGEL Avatar asked Mar 15 '18 13:03

iGEL


People also ask

How do you stash unstaged changes only?

If you have both staged and unstaged changes in your project, you can perform a stash on just the unstaged ones by using the -k flag. The staged changes will be left intact ready for a commit.

Does git stash save unstaged changes?

By default, running git stash will stash: changes that have been added to your index (staged changes) changes made to files that are currently tracked by Git (unstaged changes)


2 Answers

If you want to store the diff between the index (what's staged) and the worktree (what's not staged yet), this simply is git diff :

# store it :
git diff > stash.patch

# if you additionally want to put the unstaged changes away :
git stash -k

To apply at later these changes on the worktree (not on the index) : use git apply

git apply stash.patch

You could also use what gets stored in the stash to re-create that diff :

# stash the changes :
git stash -k

# to reapply them on the worktree at a later time :
#   the 'unstaged changes' are the diff between 
#    - what the index was (stash^2)
#    - and what the worktree was (stash)
git diff stash^2 stash | git apply -

# again : 'git apply' will apply the changes on the *worktree*, not the index
like image 96
LeGEC Avatar answered Oct 07 '22 00:10

LeGEC


Best I can come up with is:

git commit -n -m temp
git stash push -u
git reset HEAD~1

This will commit without triggering any pre-commit hooks. Then it will stash the changes that remain (i.e. the unstaged changes from before). Finally, it will reset head back to the pre-commit state (before the "temp" commit).

like image 39
scaly Avatar answered Oct 07 '22 01:10

scaly