Git clean and git stash for the rescue.
Use git clean with caution (always use
-n dry run mode)
-n before running the clean command as it will show you what files would get removed.
-d Normally, when no is specified, git clean will not recurse into untracked directories to avoid removing too much. Specify -d to have it recurse into such directories as well. If any paths are specified, -d is irrelevant; all untracked files matching the specified paths (with exceptions for nested git directories mentioned under –force) will be removed.
--force If the Git configuration variable clean.requireForce is not set to false, git clean will refuse to delete files or directories unless given -f or -i. Git will refuse to modify untracked nested git repositories (directories with a .git subdirectory) unless a second -f is given.
git clean -n -d git clean -n -d -f
Now run without
-n if output was what you intend to remove.
git clean -d -f
git clean will only remove untracked files that are not ignored. Any file that matches a pattern in your .gitignore or other ignore files will not be removed. If you want to remove those files too, you can add a
-x to the clean command.
git clean -f -d -x
There is also interactive mode available
-i with the clean command
git clean -x -i
If you are not 100% sure that deleting your uncommitted work is safe, you could use stashing instead
git stash --all
Before you use
stash --all note: If the
--all option is used, then the ignored files are stashed and cleaned in addition to the untracked files.
git stash push --keep-index
If the –keep-index option is used, all changes already added to the index are left intact. Your staged changes remain in your workspace, but at the same time, they are also saved into your stash.
git stash without any arguments is equivalent to
git stash push.
git stash push -m "name your stash" // before git stash save (deprecated)
Stashing based on the used flags can clear your directory from unstaged / staged files by writing them to stash storage. I give’s flexibility to retrieve the files at any point in time using stash with apply or pop. Then if you are fine with removing your stashed files you could run:
git stash drop // or clean
To see full instruction on how to work with stash see this How to name and retrieve a stash by name in git?