Stash just a single file

GitGit Stash

Git Problem Overview


I'd like to be able to stash just the changes from a single file:

git stash save -- just_my_file.txt

The above doesn't work though. Any alternatives?

Git Solutions


Solution 1 - Git

If you do not want to specify a message with your stashed changes, pass the filename after a double-dash.

$ git stash -- filename.ext

If it's an untracked/new file, you will have to stage it first.

However, if you do want to specify a message, use push.

git stash push -m "describe changes to filename.ext" filename.ext

Both methods work in git versions 2.13+

Solution 2 - Git

I think stash -p is probably the choice you want, but just in case you run into other even more tricky things in the future, remember that:

Stash is really just a very simple alternative to the only slightly more complex branch sets. Stash is very useful for moving things around quickly, but you can accomplish more complex things with branches without that much more headache and work.

# git checkout -b tmpbranch
# git add the_file
# git commit -m "stashing the_file"
# git checkout main

go about and do what you want, and then later simply rebase and/or merge the tmpbranch. It really isn't that much extra work when you need to do more careful tracking than stash will allow.

Solution 3 - Git

You can interactively stash single lines with git stash -p (analogous to git add -p).

It doesn't take a filename, but you could just skip other files with d until you reached the file you want stashed and the stash all changes in there with a.

Solution 4 - Git

The best option is to stage everything but this file, and tell stash to keep the index with git stash save --keep-index, thus stashing your unstaged file:

$ git add .
$ git reset thefiletostash
$ git stash save --keep-index

As Dan points out, thefiletostash is the only one to be reset by the stash, but it also stashes the other files, so it's not exactly what you want.

Solution 5 - Git

Just in case you actually mean 'discard changes' whenever you use 'git stash' (and don't really use git stash to stash it temporarily), in that case you can use

git checkout -- <file>

Note that git stash is just a quicker and simple alternative to branching and doing stuff.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEoghanMView Question on Stackoverflow
Solution 1 - GitsealocalView Answer on Stackoverflow
Solution 2 - GitWes HardakerView Answer on Stackoverflow
Solution 3 - GitBenjamin BannierView Answer on Stackoverflow
Solution 4 - GitCharlesBView Answer on Stackoverflow
Solution 5 - GitDeveshView Answer on Stackoverflow