DEV Community

foadlind
foadlind

Posted on • Originally published at practicalgit.com

Need to stash untracked files? There is a way!

You are in the middle of some work. You have created a bunch of new files and edited some existing ones when your boss comes and tells you to deal with an emergency bug fix. You realize you need to switch branches but your work is incomplete and you don't want to commit it just yet.

Stashing your changes is the best way to go. However, the default behavior of git stash is to stash only the tracked files. The untracked files will remain in your repo. Sometimes that is ok. You can have them there while you switch branches and deal with the emergency. But, in some occasions, their existence might interfere with other things (like changing the behavior of the software, or getting accidentally added to a commit).

I prefer to stash the untracked files every time I need to switch branches. That way I get a clean repo to work with. Less thinking required, and less room for error. It's the safest option.

So how do you stash both tracked AND untracked files?

Using:

$ git stash --include-untracked
# or the shorter alternative:
$ git stash -u
Enter fullscreen mode Exit fullscreen mode

"Will this include the files in my .gitignore?"

No. This will only include the untracked files you see when you do git status. If you want to stash files included in .gitignore, use git stash --all.

"How do I see what I have just stashed?"

To see all tracked files you just stashed use git show stash. To see all the untracked files you just stashed use git show stash@{0}^3. Unfortunately there is no way, that I know of, to see both the tracked and untracked stashed files using one command. This is due to the way Git stores and applies stashed changes.

signup

Top comments (2)

Collapse
 
aaronbassett profile image
Aaron Bassett

You can add this alias to have a single command to see both tracked and untracked:

[alias]
    showstash = "!if test -z $1; then set -- 0; fi; git show --stat stash@{$1} && git show --stat stash@{$1}^3 2>/dev/null || echo No untracked files -"

To see all the files in the stash (both tracked and untracked), I added this alias to my config:

showstash = "!if test -z $1; then set -- 0; fi; git show --stat stash@{$1} && git show --stat stash@{$1}^3 2>/dev/null || echo No untracked files -"

It takes a single…

Collapse
 
sebbdk profile image
Sebastian Vargr

Commit and rebase later?