Git stash single untracked file?

If you only have this one untracked file you can do:

git add -u
git stash --include-untracked --keep-index

And that will add only untracked files to the stash, and remove them from the working directory.

If you have several untraked files and you want to include just this one to the stash, then you will have to do a commit, then the stash of the single file and then a reset

git add -u
git commit -m "temp commit"
git add my_file_to_stash
git stash
git reset --hard HEAD^

The subtlely here is that when you recover the stash later, that file will be added to the index. That is probably a good thing, as it will remind you that this file is important.


Going off the information provided in the other answers, I created a script, git-stash-selection, which I use aliased to gsts:

#!/bin/sh
#
# Git stash only a selection of files, with a message.
#
# Usage:
#   git-stash-selection [<message>] [<paths>...]

message=$1
shift
stash_paths="$*"
git add --all
git reset $stash_paths
git commit --allow-empty -m "temp - excluded from stash"
git add --all
git stash save $message
git reset --soft HEAD^
git reset

I've provided full details in another answer of the method this uses and why a number of simpler commands don't work.

Edit: This might be able to be improved using this patch method instead of committing. Or maybe using another stash


In git version 2.21.0 (Windows MingW64)

You can do:

git stash push --include-untracked -- db/migrate/20161212071336_add_paranoid_fields.rb

Only the specified file is included in the stash. You can provide multiple files (both untracked and tracked) and what you specify will be stashes and checked out as normal, the other files remain as is.

Tags:

Git

Git Stash