Skip to content

Chapter 2 of 8

Cleaning the Working Tree and Fixing .gitignore

Untracked files are handled separately from modifications, and git clean is the dedicated tool for removing them. By default it removes untracked files; adding -d extends it to untracked directories. A dry run with git clean -nd lists everything that would be deleted without touching the disk, which is the safest way to preview before running the real git clean -fd. Forgetting to clean untracked files leads to a common two-step cleanup: git restore . clears modifications in tracked files, and git clean -fd then sweeps up anything untracked that remains. Because git clean operates on files Git has never recorded, it is genuinely destructive and cannot be undone by Git itself.

Sometimes a .gitignore rule refuses to take effect because the offending file is already tracked by Git. The fix is git rm --cached path, which removes the file from the index (and from the next commit) without deleting it from your working tree; commit the removal and the ignore rule will start working. To see exactly which rule is being applied to a path, use git check-ignore -v path, and to see everything Git is currently ignoring, add --ignored to git status. Note that Git cannot track empty directories at all, so the convention is to commit a placeholder such as .gitkeep whenever a folder's presence needs to be preserved across checkouts.

All chapters
  1. 1Undoing Commits and Local Changes
  2. 2Cleaning the Working Tree and Fixing .gitignore
  3. 3Rewriting History with Rebase
  4. 4Merging and Conflict Resolution
  5. 5Stashing Work in Progress
  6. 6Branches, Remotes, Tags, and Force-Push Safety
  7. 7Investigating and Searching History
  8. 8Advanced Recovery, Configuration, and Housekeeping

Drill it

Reading is not remembering. These come from the Git Recovering From Common Mistakes deck:

Q

Undo the last commit but keep changes staged.

git reset --soft HEAD~1

Q

Undo the last commit AND discard changes.

git reset --hard HEAD~1  ⚠ destructive.

Q

Undo the last commit but keep changes unstaged in the working tree.

git reset --mixed HEAD~1 (the default).

Q

Amend the last commit message.

git commit --amend -m 'new message'