In Git, stashing allows you to clear your working directory and switch branches without losing your current work. However, by default, git stash
does not include untracked files (files that are new or are explicitly ignored by Git). This guide explains how to include untracked files in your stash, ensuring that all aspects of your current work can be saved temporarily.
Understanding git stash
git stash temporarily shelves (or stashes) changes you've made to your working directory so you can work on something else, and then come back and re-apply them later on. The stashed changes are saved on a stack, where you can reapply them as needed.
Step 1: Stashing untracked files
To stash changes, including untracked files, you need to use the --include-untracked
or -u
option with git stash
. This command saves both your staged and unstaged changes, as well as any files in the working directory that Git is not tracking.
Using the Command
To stash your local changes, along with untracked files, run:
git stash -u
Step 2: Viewing Stashed Changes
After stashing your changes, including the untracked files, you can view the list of stashed entries using:
git stash list
This command will show you a list of all stashed changes. Each entry is indexed starting from stash@{0}
for the most recent stash.
Step 3: Reapplying Stashed Changes
To reapply the changes you've stashed, use the git stash pop
command. This command applies the stashed changes and removes them from the stash stack.
git stash pop
If you want to keep the stash in your stack, while still applying the changes locally, you can use git stash apply
instead:
git stash apply
If you have multiple stashes, you can specify which stash to apply or pop by providing the stash identifier:
git stash apply stash@{0}
Step 4: Managing multiple stashes
If you frequently use stashing, you may end up with multiple stashed entries. You can manage these individually by referring to their index in the stash list.
Dropping a stash: If you want to remove a specific stash from the stack:
Terminalgit stash drop stash@{0}Clearing all stashes: If you decide you no longer need any of the stashed entries:
Terminalgit stash clear
Additional tips
Stashing specific files: If you want to stash only specific files (including untracked ones), you can specify them with the command:
Terminalgit stash push -u -- filename1 filename2Handling merge conflicts: If applying a stash results in merge conflicts, you will need to resolve these conflicts manually. After resolving conflicts, complete the process by adding the resolved files to the index using
git add
, and then continue with your work. See this detailed guide on resolving merge conflicts for more info.Using stashes for experiments: Stashes are great for trying out ideas without committing to the changes. If an experiment doesn’t work out, you can simply drop the stash.
For further reading on stashing in Git, see the official Git documentation.