Search code examples
gitgit-stash

Git stash single untracked file?


Question

I have a couple of edited files as listed below, and I also have some newly created files:

Stash File List

Now I want to stash the untracked file (in this case, it's db/migrate/20161212071336_add_paranoid_fields.rb) but not stash the changed files.

How should I do that?

Why I want to stash a single untracked file

I created this file at first, and then I realised that I don't need it immediately (it needs to be deleted in order for my program to work correctly); but I might need it in the future.

What I've searched (and not giving me an answer), and the reason why they don't help


Solution

  • 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.