Appearance
Git reset and clean — working tree, index, and HEAD manipulation for DevOps
git reset moves the current branch HEAD, updates the index (staging area), and optionally rewrites the working tree — all in one command. git clean removes untracked files and directories. Together they are the sharpest tools in Git's workshop for CI state management, emergency undo, build artifact cleanup, and index surgery.
The existing git-revert-rollbacks.md covers forward-moving rollbacks on shared branches. This guide covers everything else: local undo, index manipulation, branch detachment, and working-tree sanitation — patterns that belong in every CI pipeline and every engineer's muscle memory.
1. What git reset actually does
git reset is three operations in one, controlled by a mode flag:
| Mode | HEAD | Index (staging) | Working tree |
|---|---|---|---|
--soft | Moves | Unchanged | Unchanged |
--mixed (default) | Moves | Reset to match HEAD | Unchanged |
--hard | Moves | Reset to match HEAD | Reset to match HEAD |
Think of it as peeling back layers. --soft touches only the branch pointer. --mixed also unstages everything. --hard throws away all local changes.
The default mode: --mixed
bash
# Unstage all files (keep working tree intact)
git reset
# Unstage specific paths only
git reset -- path/to/file
git reset HEAD -- path/to/file # same thing, explicitThis is how you undo git add without losing edits. It's the most commonly needed operation and the default mode requires no flag.
--soft: move the branch pointer only
bash
# Undo the last commit but keep everything staged
git reset --soft HEAD~1
# Squash the last N commits into one
git reset --soft HEAD~3
git commit -m "squashed three commits into one"The working tree and index stay exactly as they were. The branch pointer moves. This is the foundation of git commit --amend and manual squash workflows.
--hard: full reset
bash
# Throw away all uncommitted changes (staged + unstaged)
git reset --hard HEAD
# Discard everything after a specific commit
git reset --hard v2.3.0
# Move HEAD back N commits, discard everything
git reset --hard HEAD~5There is no undo for --hard once the changes are gone from disk. The reflog preserves the old HEAD (see section 7), but uncommitted changes that were never staged are lost. Use git stash as insurance before a --hard on a dirty working tree.
Pathspec mode
When given paths, git reset skips the branch-pointer step entirely and only updates the index:
bash
# Unstage a single file (like git restore --staged)
git reset -- main.go
# Unstage everything matching a pattern
git reset -- '*.lock'This is the safe way to selectively unstage in CI scripts without affecting the working tree or HEAD.
2. git clean — removing untracked files
git clean removes files and directories not tracked by Git. It's the companion to git reset --hard for achieving a pristine working tree.
bash
# Dry-run: show what would be removed
git clean -n
# Remove untracked files (not directories)
git clean -f
# Remove untracked files and directories
git clean -fd
# Remove everything including gitignored files
git clean -fdx
# Remove only gitignored files (leave untracked-but-not-ignored)
git clean -fX| Flag | Effect |
|---|---|
-n | Dry-run preview |
-f | Force (required unless clean.requireForce is false) |
-d | Also remove untracked directories |
-x | Remove gitignored files too (default: skip .gitignore-matched) |
-X | Remove only gitignored files, leave other untracked |
-e <pattern> | Exclude a pattern from removal |
-i | Interactive mode |
When each variant matters
git clean -fd— CI runner before a build that generates artifacts. Removes leftover build outputs that aren't gitignored.git clean -fdx— Full clean: restores the repo to the exact state of a fresh clone. Use when the build system caches intermediate files in.cache/or.next/directories.git clean -fX— Wipe only gitignored artifacts (node_modules, dist/, .venv) but keep untracked config files a developer may have placed there.
3. The three-argument reset: splitting a branch
The full git reset signature is git reset [<tree-ish>] [-- <pathspec>]. The <tree-ish> defaults to HEAD when omitted. But when you supply a specific tree, you can reset the index to match any commit, tag, or tree — not just HEAD.
bash
# Stage files exactly as they were in a specific commit
git reset v2.3.0 -- src/config.json
# Compare index against an old state
git diff --cached v2.3.0This is how you "cherry-pick a file's state" from any revision into the index without touching HEAD. Useful when a hotfix branch needs a config file from the release tag but the code stays on main.
4. DevOps CI/CD patterns
Pattern 1: Pristine checkout for reproducible builds
bash
# Inside a CI runner before a build step
git reset --hard HEAD
git clean -fdxThis guarantees the working tree matches HEAD exactly with no stale artifacts. Every CI runner should start with this unless it's using incremental caching intentionally.
Pattern 2: Selective unstage in CI
When a CI script stages files it shouldn't commit:
bash
# Unstage generated files before a commit
git reset -- 'dist/*'
git reset -- '*.min.js'
# Verify nothing unwanted is staged
git diff --cached --name-onlyPattern 3: Build matrix cleanup with worktrees
bash
# In each parallel worktree before a matrix build
git -C "$WORKTREE_PATH" reset --hard HEAD
git -C "$WORKTREE_PATH" clean -fdxPattern 4: Emergency local undo (uncommitted changes)
bash
# Abandon all local changes and go back to HEAD
git reset --hard HEAD
git clean -fd
# Or preserve stashes in case
git stash push -m "auto-save before reset"
git reset --hard HEADPattern 5: Squash the last N commits before push
bash
git reset --soft HEAD~3
git commit -m "feat: combined three WIP commits into one"This keeps the working tree unchanged and the index populated with all changes from the last three commits. A single new commit replaces them.
Pattern 6: CI preflight working-tree assertion
bash
# Fail the pipeline if the working tree is dirty (uncommitted changes)
if ! git diff --quiet; then
echo "Error: working tree has uncommitted changes"
exit 1
fi
# Fail if untracked files exist
if [ -n "$(git status --porcelain)" ]; then
echo "Error: repo has untracked or modified files"
exit 1
fiPattern 7: ORIG_HEAD based rollback in CI
Before a git pull --rebase or merge, Git saves the original HEAD to ORIG_HEAD. Use it for automatic rollback:
bash
git pull --rebase origin main || {
echo "Rebase failed, rolling back"
git reset --hard ORIG_HEAD
exit 1
}5. git reset vs git restore — when to use which
The modern git restore split checkout's index and tree operations into their own commands. There's deliberate overlap with git reset:
| Operation | git reset | git restore |
|---|---|---|
| Unstage a file | git reset -- file | git restore --staged file |
| Discard working tree changes | git checkout -- file | git restore file |
| Move HEAD (branch pointer) | git reset --soft/mixed/hard <ref> | N/A |
| Squash commits | git reset --soft HEAD~N | N/A |
| Restore file to specific commit | git reset <commit> -- file | git restore --source=<commit> file |
Use git restore for file-level index and tree operations. Use git reset when you need to move the branch pointer (squash, undo commits, change base). The reset command remains the only way to manipulate HEAD.
6. ORIG_HEAD and recovery
Before certain operations (merge, pull, reset), Git saves the previous HEAD value in ORIG_HEAD. This is a safety net:
bash
# After a hard reset that went too far
git reset --hard ORIG_HEAD
# After a botched merge that was reset away
git merge ORIG_HEADORIG_HEAD is overwritten by the next destructive operation. It is not a permanent backup — use tags or branches for that.
Reflog: the real safety net
If ORIG_HEAD has already been overwritten:
bash
# Find the commit you want
git reflog
# Reset to it
git reset --hard HEAD@{3}The reflog retains every HEAD movement for 90 days by default (or 30 days for unreachable commits). See git-reflog-forensics.md for the full recovery guide.
7. Common mistakes and pitfalls
Mistake 1: git reset --hard on a dirty working tree
You lose unstaged, uncommitted work. There is no recovery for unstaged changes after a --hard reset.
Prevention: Always git stash before a --hard reset if the working tree might be dirty. Or use git stash push -m "pre-reset $(date)" as insurance.
bash
# Safe pattern
git stash push -m "auto-save before hard reset"
git reset --hard HEAD
# If you need the changes back: git stash popMistake 2: Resetting a shared branch
git reset rewrites history. Pushing a reset branch with --force destroys commits others may have based work on. Use git revert on shared branches.
Prevention: Only git reset on branches that exist only on your machine. Use git revert for any branch pushed to a shared remote.
Mistake 3: git clean -fdx inside a Docker build context
Removes the Dockerfile. Also removes .dockerignore, the source tree, and anything not tracked.
Prevention: Always run git clean -n first in CI to preview what will be removed. If the output includes files the build needs, adjust your .gitignore or exclude patterns.
Mistake 4: Forgetting -- before pathspec
bash
# Dangerous: if "main.go" looks like a branch name, this does something else
git reset main.go
# Safe: always use -- before paths
git reset -- main.goWithout --, Git tries to interpret the argument as a tree-ish first. If a branch or tag with that name exists, the behavior changes silently.
Mistake 5: Assuming git reset --hard preserves the index
It does not. --hard resets the index to match the target commit, discarding any staged changes. If you staged changes you want to keep, commit them or stash them first.
Mistake 6: git clean without -f or -n
On most systems clean.requireForce defaults to true, so git clean without -f prints a warning and does nothing. But on a system where it's been disabled globally, a bare git clean removes everything untracked. Always preview with -n first.
8. Decision table
| What you need | Command |
|---|---|
| Unstage everything, keep edits | git reset |
| Unstage one file | git reset -- file |
| Undo last commit, keep changes staged | git reset --soft HEAD~1 |
| Undo last N commits, unstage everything | git reset HEAD~N |
| Discard all local changes (committed) | git reset --hard HEAD |
| Discard all local changes (committed) + untracked | git reset --hard HEAD && git clean -fd |
| Discard everything including gitignored | git reset --hard HEAD && git clean -fdx |
| Restore file to its state in another commit | git reset <commit> -- file |
| Squash last N commits | git reset --soft HEAD~N && git commit -m "..." |
| Remove untracked build artifacts | git clean -fd |
| Wipe node_modules and other gitignored dirs | git clean -fX |
| Rollback failed rebase | git reset --hard ORIG_HEAD |