What is git stash?

git stash is a powerful command that allows you to temporarily shelve(or save) changes in your working directory, including untracked files, without committing them to the repository.
This can be useful when you need to switch branches, pull changes from remote repository, or just clean up your working directory without losing any changes.

Untracked files

Untracked files are those which are not yet committed. They reside in your working directory as local changes only.
These are called untracked because they are not known to git.

You can see untracked files when you execute git status as shown below

$ git status
On branch master
Your branch is up to date with ‘origin/master’.

Untracked files:
(use “git add …” to include in what will be committed)
version.txt

How to stash untracked files

By default, when you execute git stash command, it will only stash the files that are known to it, also called tracked files.
These files are already committed into git repository and you have modified them.

So, if you execute git stash and all changes are in new or untracked files only, git will say that there are no local changes as shown below

$ git stash
No local changes to save

git stash command provides a -u flag or --include-untracked option, which also considers untracked files and includes them in stash.

So, above command when executed with any of these flags will stash untracked files as well. See below output.

$ git stash -u
Saved working directory and index state WIP on master: edacb58 Merged in HTML changes-1695207515540

View untracked files

Just like git stash does not include untracked files in a stash by default, it will not show untracked files when you try to see the contents of a stash with git stash show command.

So, if we execute git stash show on the above stash, the output will be empty.

To see untracked files included in a stash, use -u or --include-untracked flag with git stash show as shown below

$ git stash show -u
version.txt | 4
++++
1 file changed, 4 insertions(+)

This will show the contents of the most recent stash.

To see untracked files in another stash, refer it with stash@{index}. Examples,

# show untracked files in second stash
git stash show stash@{1} -u

# show untracked files in fifth stash
git stash show stash@{4} -u

index starts with 0.
Remember that -u will show both tracked and untracked files in output.

Conclusion

By default, any of git stash command does not consider untracked files.
To add untracked files in a stash, use any of the below commands

git stash add -u
git stash add --include-untracked

To see untracked files contained in stash, use any of the below commands

# refer recent or topmost stash
git stash show -u
git stash show --include-untracked

# refer stash by index
git stash show stash@{1} -u
git stash show stash@{1} --include-untracked

Hope the article was useful.