2

I want to stash a single file. Since git stash does not allow a filename as a parameter, I have to use git stash -p and select the file among the rest of changes.

This works fine if changes not staged for commit do not include many files, or if the file I want to stash is one of the first ones.

However, if there are many files and the one I want to stash is to the end of the list, I have to go through all the other ones until I get to the desired one. And this is a bit tedious.

So I was wondering: is there a way to define the order in which the files not staged for commit appear upon doing git stash -p?

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 1
    Why do you need this? Could [this](http://stackoverflow.com/questions/3040833/stash-only-one-file-out-of-multiple-files-that-have-changed-with-git) work for you? – Francesco Apr 12 '16 at 08:29
  • It's worth considering that `git stash` simply creates a commit—well, more precisely, at least two, sometimes three, commits—that are not on your current branch (and in fact not on *any* branch). Since branch labels are moveable, you can create commits and then shuffle the labels around and make it look like you created the commits on some other branch(es). The tools for creating commits *do* allow you to specify particular files, so you might want to consider using them here. – torek Apr 12 '16 at 17:30
  • @torek good hint! It is a pity, though, that `git stash` does not allow as an option something as simple as a file name : ) – fedorqui Apr 12 '16 at 21:00

1 Answers1

1

You could do this:

git add file
git stash -k -u
git stash
git stash pop stash@\{1\}
git checkout file

It's totally a hack, and it will work only if you don't have staged changes before doing this, but as far as I know there is no good way to do what you need.

First, we add file to the index, then we stash everything else (-k to keep file in the index and -u to also take untracked files), then stash file. The last two commands are cleanup: we apply the first stash to retrieve everything, then checkout file to remove its changes (as stash does). In the end, you should have your stash with only your changes on file in it and your directory unchanged except for file which is back to the HEAD revision.

Julien Lopez
  • 1,794
  • 5
  • 18
  • 24
  • 1
    Interesting workaround, thanks! It is a bit dangerous, since it empties the stash as you mention. Note, by the way, there is no need to escape the braces in `stash@{1}`. – fedorqui Apr 12 '16 at 21:10
  • 1
    @fedorqui It shouldn't mess up your stash, but it will reset any `git add` you did before this. You're right about the escaping I think, I let my auto-completion on zsh convince me it was needed. :-) – Julien Lopez Apr 13 '16 at 08:47