TechEarl

How to Discard Local Changes in Git

Discard local changes in Git with restore, checkout, and clean. Throw away edits to tracked files, delete untracked files, reset to the last commit, then undo a commit, choose reset or revert, untrack a file, and recover lost commits with reflog.

Ishan KarunaratnePublished ⏱️ 17 min readUpdated
Share thisCopied
Discard local changes in Git with restore and clean, then undo the last commit, pick reset or revert, untrack a file, and recover commits with reflog.

To discard local changes in Git and go back to the last commit, run git restore <file> for one file or git restore . for all of them. On Git before 2.23, use git checkout -- <file> instead. To delete files Git is not yet tracking, you need git clean -fd. None of this is recoverable once it runs, so be sure before you press enter.

That is the whole answer for uncommitted edits. Further down, the same page covers the rest of the undo toolkit: undoing the last commit, choosing reset or revert, recovering lost commits with the reflog, and removing a file from Git without deleting it.

What "local changes" actually means

When you edit files in a repository, Git sorts them into states. Knowing the state tells you which command to reach for. If the difference between these is fuzzy, the staging area walkthrough is worth ten minutes first.

StateWhat it meansHow to discard it
Modified, tracked, unstagedYou edited a file Git already knows about, no git add yetgit restore <file>
Modified, tracked, stagedSame, but you ran git add on itgit restore --staged <file> then git restore <file>
UntrackedA new file Git has never seen (no git add ever)git clean -f
EverythingThrow away the whole working treegit reset --hard plus git clean -fd

Run git status first, every time. It tells you exactly which bucket each file is in, and it spells out the discard command for that bucket right in its output. Reading status before discarding is the single habit that prevents most "I lost my work" moments.

Discard changes to a tracked file

This is the common case: you changed a file, the change is wrong, and you want the file back the way it was at the last commit.

bash
# discard changes to one file
git restore path/to/file.js

# discard changes to everything in the working tree
git restore .
Discarding tracked and untracked changes with git restore and git clean
git restore drops tracked edits; git clean -fd removes untracked files.

git restore arrived in Git 2.23 (August 2019) to split the overloaded git checkout into two clearer commands: git restore for files, git switch for branches. It is the modern, recommended way to do this, because checkout made it easy to fat-finger a branch name and lose your edits.

On an older Git, the equivalent is:

bash
# pre-2.23 syntax, still works on every version
git checkout -- path/to/file.js
git checkout -- .

The -- matters. It tells Git "everything after this is a file path, not a branch or flag," which avoids ambiguity if a file happens to share a name with a branch. Both forms do the same thing: overwrite your working copy with the version from HEAD, the last commit on your current branch.

Discard a change you already staged

If you ran git add on the file, it is staged, and a plain git restore will not touch it. Unstage it first, then discard:

bash
# step 1: move it out of the staging area (the file keeps your edits)
git restore --staged path/to/file.js

# step 2: now discard the edits in the working tree
git restore path/to/file.js

The two-step is deliberate. git restore --staged only resets the staged copy back to HEAD; your edits are still sitting in the working file. The second git restore is what actually throws those edits away. If you only want to unstage and keep editing, stop after step one (git restore --staged . unstages everything; it replaces the old git reset HEAD file). A common reason to be here at all is that a pull or merge refused to run and complained that your local changes would be overwritten by merge; discarding the staged and working edits is one way to clear that block.

Delete untracked files with git clean

Here is the trap that catches beginners: git restore and git checkout only operate on files Git is already tracking. A brand-new file you have never committed is untracked, and Git will leave it completely alone. To remove untracked files you need git clean.

Always do a dry run first. -n shows what would be deleted without deleting anything:

bash
# DRY RUN: list what clean would remove, delete nothing
git clean -n
git clean -nd     # include untracked directories in the preview

Once you are happy with that list, run it for real:

bash
# delete untracked files
git clean -f

# delete untracked files AND untracked directories
git clean -fd

# also remove files your .gitignore is ignoring (build output, etc.)
git clean -fdx

The flags:

  • -f is "force." Git refuses to delete files without it, on purpose, because this is destructive.
  • -d extends the delete to untracked directories, not just loose files.
  • -x also removes files matched by your .gitignore rules, like node_modules or a build/ folder. Use this one carefully; it wipes things you usually want to keep, like local env files.

A common and damaging mix-up: uppercase -X is not "only untracked files." It removes only ignored files and leaves your real untracked files in place.

You want to deleteCommand
Untracked files and foldersgit clean -fd
Only ignored files (build output, caches)git clean -fdX
Untracked and ignored, everythinggit clean -fdx

git clean -fdx is the nuclear option for a truly pristine checkout. I reach for it when a build is poisoned by stale artifacts and I want the directory to look exactly like a fresh git clone.

Throw everything away and reset to the last commit

To return the entire working tree to the last commit, both tracked edits and untracked junk, you need two commands. reset --hard handles tracked files; clean -fd handles the untracked ones.

bash
# discard all changes to tracked files
git reset --hard

# then remove every untracked file and directory
git clean -fd

git reset --hard rewinds tracked files to HEAD and blows away both staged and unstaged edits in one move. It does not touch untracked files, which is why the clean is still needed for a complete wipe. If you want to reset to a specific commit rather than the current one, name it: git reset --hard <commit-hash>.

A safer middle ground, if you might want the work back later, is to stash instead of discard:

bash
# tuck everything away instead of deleting it
git stash --include-untracked

That puts your changes on a stack you can restore with git stash pop. When you are not fully sure you want the work gone, stash it; the git stash guide covers the workflow. Stashing costs nothing and buys you an undo.

This is irreversible. Really.

The commands above do not move files to a trash can. They overwrite or delete them at the filesystem level. Git's safety net, git reflog, only tracks committed history. Edits you never committed leave no trace once git restore, git reset --hard, or git clean runs.

  • Committed work can almost always be recovered, even after a bad reset --hard, using the reflog. The commit is still in the object database.
  • Uncommitted work (anything you discard here) is gone. No reflog entry, no dangling commit, nothing to recover.

So the discipline is simple: run git status to see what you are about to lose, run git clean -n before any real git clean, and when in doubt, git stash instead of discard. Committing early and often also helps, because a commit is a recoverable checkpoint.

How to undo anything in Git

Discarding uncommitted edits is one row of a bigger map. Almost every undo in Git comes down to one question: what state is the change in right now? Pick your row:

SituationCommand
Discard unstaged edits to a filegit restore path/to/file
Unstage a staged file (keep the edits)git restore --staged path/to/file
Reword the last commit messagegit commit --amend
Undo the last commit, keep the changesgit reset --soft HEAD~1
Undo the last commit, throw the changes awaygit reset --hard HEAD~1
Undo a commit you have already pushedgit revert <sha>
Delete untracked files and foldersgit clean -fd (preview with -nd first)
Stop tracking a file but keep it on diskgit rm --cached path/to/file
Recover something you think you lostgit reflog

The old muscle memory, git checkout -- file and git reset HEAD file, still works and is not deprecated. But git restore (files) and git switch (branches) were added in Git 2.23 precisely because checkout did too many jobs, and they are what I reach for now. The sections below cover the commit-level rows.

Undo the last commit

To undo your last Git commit but keep all the changes staged, run git reset --soft HEAD~1. The commit disappears, your files are untouched, and everything is staged ready to recommit. Which command you actually want depends on two questions: do you want to keep the changes, and have you already pushed the commit.

bash
# Undo the commit, keep changes staged (most common)
git reset --soft HEAD~1

# Undo the commit, keep changes but unstage them
git reset --mixed HEAD~1   # or just: git reset HEAD~1

# Undo the commit AND throw the changes away (destructive)
git reset --hard HEAD~1

# Just fix the last commit's message or add a forgotten file
git commit --amend

# Undo a commit you already pushed (safe for shared branches)
git revert HEAD
Undoing the last commit with git reset --soft in the terminal
git reset --soft HEAD~1 removes the commit but keeps your changes staged.

HEAD~1 means "one commit before the current HEAD," so the reset moves the branch pointer back by one commit. After --soft, git status shows your changes staged:

text
On branch main
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        modified:   src/app.js

Recommit when you are ready with git commit -m "A better message this time". Use --mixed (the default mode) instead when you want to re-stage selectively, for example to split one fat commit into several. Use --hard only for a commit full of junk you never want to see again; if you panic afterwards, the reflog usually still has it.

Fix the last commit with amend

Sometimes you do not want to undo the commit at all, just fix a typo in the message or add a forgotten file:

bash
git commit --amend -m "The corrected commit message"

# add a file you forgot, keeping the same message
git add forgotten-file.js
git commit --amend --no-edit

--amend replaces the last commit with a new one (new hash), so it is still a history rewrite.

Have you pushed? That decides everything

  • Not pushed yet (local only): rewrite history freely. reset and amend are fine.
  • Already pushed to a shared branch: do not rewrite history; other people may have pulled that commit. Use revert (next section). Rewriting a commit someone already pulled is how you end up with divergent branches and force-push arguments.
SituationCommandKeeps changes?Rewrites history?
Committed too early, want to recommitgit reset --soft HEAD~1Yes, stagedYes (local only)
Want to re-stage selectivelygit reset HEAD~1Yes, unstagedYes (local only)
Commit was pure junk, drop itgit reset --hard HEAD~1No, discardedYes (local only)
Just a bad message or a missing filegit commit --amendYesYes (local only)
Commit is already pushed and sharedgit revert HEADNew inverse commitNo, adds a commit

HEAD~2 walks back two commits, HEAD~3 three, and so on: git reset --soft HEAD~3 undoes the last three local commits but keeps their combined changes staged. For surgical edits across several commits (reword, drop, combine specific ones), interactive rebase is the right tool.

git reset vs git revert

git reset and git revert both undo work in opposite ways. reset moves your branch pointer backward and rewrites history, as if the later commits never happened. revert leaves history intact and adds a brand new commit that cancels out an earlier one. The rule: reset on commits you have not shared yet, revert on anything already pushed to a branch other people pull from.

git resetgit revert
What it doesMoves the branch pointer to an older commitAdds a new commit that reverses an old one
HistoryRewritten (commits dropped from the branch)Preserved (everything stays in the log)
Safe on shared branchesNoYes
Creates a new commitNoYes (one per reverted commit)
Touches working treeDepends on mode (--soft, --mixed, --hard)Yes, applies the inverse diff
Recoverable if wrongVia the reflog, time-limitedTrivially, just revert the revert

The three reset modes

git reset always moves the branch pointer. What it does to the staging area and your working files depends on the mode:

ModeBranch pointerStaging areaWorking tree
--softMoved backKept (changes stay staged)Kept
--mixed (default)Moved backReset (changes unstaged)Kept
--hardMoved backResetReset (changes discarded)

Why revert is the safe choice on shared branches

Once you have pushed a commit, its hash is part of the history everyone else has pulled. If you reset past it and force-push, your branch no longer contains commits other people's branches still do, and the next git pull turns into diverged history, conflicts, or someone re-pushing the commits you tried to delete. git revert only ever adds a commit, so teammates pull a normal change and nothing needs reconciling. On a protected main branch, the force-push a reset would need is blocked outright anyway.

bash
# Undo a specific public commit by hash (find it with git log --oneline)
git revert 9f1c0a2
git push

# Undo a range (each commit gets its own revert, newest first)
git revert HEAD~3..HEAD

# Stage the inverse changes without committing yet, so you can group them
git revert --no-commit 9f1c0a2

Git opens an editor with a prefilled Revert "the original subject" message; save it, or pass --no-edit. Reverting a merge commit needs the -m parent flag; the git revert docs cover the mainline-parent rule. If a revert turns out to be wrong, revert the revert.

One caveat on secrets: revert undoes the change, but a committed API key still sits in the history and can be checked out from the old commit. Rotate the key, and if it must be gone from history, follow removing a secret from Git history.

Recover lost commits with git reflog

If a bad git reset, a botched rebase, or a deleted branch seems to have wiped out commits, the work is almost always still there. Git keeps a log of every place HEAD has pointed, the reflog. Run git reflog, find the line just before things went wrong, and point a reference back at that hash.

bash
git reflog
Recovering a lost commit using git reflog and git reset
git reflog finds the commit a hard reset dropped, and reset --hard restores it.
text
e3a1f0c (HEAD -> main) HEAD@{0}: reset: moving to HEAD~3
9b7d2a4 HEAD@{1}: commit: add password reset endpoint
1c8e5f9 HEAD@{2}: commit: wire up email templates
4f6b0d3 HEAD@{3}: commit: scaffold auth routes
a2c9e88 HEAD@{4}: checkout: moving from develop to main

Each line is one move of HEAD: the hash, HEAD@{n} (how many moves ago, 0 being the latest), and the action. The reflog is local to your clone (it lives in .git/logs/ and is never pushed), and it records the old hashes that a rebase or reset --hard hides from git log.

A commit is an immutable object; a branch is a movable label. "Losing" a commit usually means the label moved off it. Git only prunes unreachable objects during garbage collection, and by default reflog entries for commits no longer reachable from any branch are kept for 30 days (gc.reflogExpireUnreachable), versus 90 days (gc.reflogExpire) for commits still on a branch. The commits you recover are the unreachable ones, so 30 days is the window that matters: weeks, not seconds.

After a bad reset

You ran git reset --hard HEAD~3 and three commits vanished. In the reflog above, HEAD@{1} (9b7d2a4) is where you were right before the reset:

bash
git reset --hard 9b7d2a4

git reset --hard HEAD@{1} also works, but the explicit hash is harder to get wrong. Stash any uncommitted edits first, since reset --hard discards them.

After a botched rebase

A rebase leaves a clear marker in the reflog:

text
7d4c1a2 (HEAD -> feature) HEAD@{0}: rebase (finish): returning to refs/heads/feature
7d4c1a2 HEAD@{1}: rebase (squash): combine auth commits
b8e3f01 HEAD@{2}: rebase (start): checkout main
2a9c6d4 HEAD@{3}: commit: add password reset endpoint

The entry just before rebase (start), HEAD@{3} here, is your branch exactly as it stood before the rebase. git reset --hard HEAD@{3} throws the rebase away. The HEAD@{n} numbers shift every time HEAD moves, so always read your own reflog.

A deleted branch

bash
git branch -D feature/checkout
text
Deleted branch feature/checkout (was 5f2a8c1).

Git prints the hash right there. If you missed it, find the branch's last position in git reflog, then recreate it: git branch feature/checkout 5f2a8c1.

reset, checkout, branch, or cherry-pick?

CommandWhat it doesUse it when
git reset --hard <hash>Moves your current branch tip to that commit and matches the working tree to itYou want the current branch to become the recovered state and have no uncommitted work to lose
git checkout <hash>Puts you on the commit in detached HEAD, leaving every branch untouchedYou want to inspect the commit first
git branch <name> <hash>Creates a new branch pointing at the commitYou are recovering a deleted branch, or want the old state on its own branch
git cherry-pick <hash>Replays just that commit on top of your current branchYou only need one lost commit's changes back

git switch -c recovered-work <hash> creates the branch and moves onto it in one step. When unsure, git checkout <hash> is the gentlest move.

The reflog cannot help with uncommitted work (it tracks commits, not your working tree), with a commit that only lived in a clone you deleted and was never pushed, or after garbage collection past the grace period (git gc --prune=now prunes unreachable commits immediately). If you ever pushed the work, git fetch and the remote-tracking branches still have it.

Remove a file from Git without deleting it

To stop Git tracking a file but keep it on your disk, run git rm --cached <file>. The --cached flag removes the file from the index without touching the copy in your working directory. This is the fix for a .env, a node_modules folder, or an IDE config you committed by accident.

bash
git rm --cached config.local.json
text
rm 'config.local.json'

The "rm" looks alarming, but the file is still in your folder. git status shows it twice, as a staged deletion and as an untracked file:

text
On branch main
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
	deleted:    config.local.json

Untracked files:
  (use "git add <file>..." to include in what will be committed)
	config.local.json

Commit the removal, then add the path to .gitignore so the next git add . does not stage it straight back in:

bash
git commit -m "Stop tracking config.local.json"
echo "config.local.json" >> .gitignore
git add .gitignore
git commit -m "Ignore config.local.json"

Adding a tracked file to .gitignore does nothing on its own; .gitignore only affects untracked files, which is why git rm --cached comes first. For a whole folder, add -r:

bash
git rm -r --cached node_modules
echo "node_modules/" >> .gitignore

It prints one rm line per file, which can be thousands for node_modules; the folder stays on disk.

CommandRemoves from Git indexDeletes file on diskWhen to use it
git rm --cached fileYesNoStop tracking, keep the file locally
git rm fileYesYesDelete the file from the repo and your disk
rm file (plain shell)No (until you commit)YesDelete on disk; Git records a deletion you still commit

If you ran git rm without --cached and the file vanished, bring it back before committing with git restore --staged config.local.json then git restore config.local.json (on Git before 2.23, git checkout HEAD -- config.local.json). If you already committed the deletion, git checkout HEAD~1 -- config.local.json restores it from the previous commit.

The file is still in your history. git rm --cached stops tracking from this commit forward; it does not scrub earlier commits. If the file held a secret, treat it as compromised: rotate it, then rewrite history to purge it.

FAQ

They do the same job for files. git restore is the newer, clearer command introduced in Git 2.23 in August 2019, and it only handles files. git checkout still works on every version but it is overloaded with branch switching too, which is why Git split it. On a modern Git, prefer git restore. On an older install, git checkout -- file is your only option.

Because the file is untracked. git restore and git checkout only operate on files Git is already tracking. To delete untracked files you have to use git clean, after a dry run with git clean -n to confirm what it will remove.

No. Uppercase -X deletes only files Git is ignoring and leaves real untracked files alone. For untracked files and folders you want plain git clean -fd. Preview with git clean -nd first.

Run git reset --hard to wipe edits to tracked files, then git clean -fd to delete untracked files and directories. Add the x flag, git clean -fdx, if you also want to remove ignored files like build output and node_modules.

No. The soft reset only moves the branch pointer back. Your file changes stay exactly as they were and remain staged, ready for you to commit again. The only reset mode that discards your changes is the hard reset.

On a branch only you use, yes, followed by a force push. On a shared branch like main, no. Resetting rewrites history, and anyone who already pulled the commit will end up out of sync. Use git revert instead, which adds a new commit that undoes the change.

If the work was committed, you can usually recover it through the reflog: find the old hash with git reflog and reset or branch back to it. If it was uncommitted, no. These commands delete uncommitted edits at the filesystem level and leave no recovery point.

By default, reflog entries for commits no longer reachable from a branch are kept for 30 days (gc.reflogExpireUnreachable) before garbage collection may prune them; entries for commits still on a branch are kept for 90 days (gc.reflogExpire). Lost commits are the unreachable ones, so plan around 30 days.

No. It only stops tracking the file from the new commit forward. If the file was a secret, rotate it and rewrite history to purge it.

Sources

Authoritative references this article was fact-checked against.

Tagsdiscard local changes gitGitVersion Controlgit restoregit cleangit resetgit revertgit reflogundo git commitgit rm --cached

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

List the files changed in git from the command line: working tree, staged, last commit, between two branches, and piping the list to a linter to check only what changed.

How to List the Files Changed in Git

List the files changed in git: working tree, staged, the last commit, between branches, or since N commits. Then pipe the list straight into a linter so you only check what changed.

Disable root login over SSH and the console, lock the root password, switch sshd to keys only, and add a pre-auth banner without locking yourself out.

How to Disable Root Login on Linux

Disable direct root login over SSH and on the console, lock the root password, switch sshd to key-only authentication, audit its algorithms with ssh_scan, and add a pre-auth login banner, without locking yourself out.

Clone a team's Git repo, branch, commit, push, and open a pull request. Plus fork vs clone, syncing a fork, and 'remote origin already exists'.

How to Start Working on an Existing Git Project

Joining a team and need to start contributing to an existing Git repo? Here is the exact path: clone, install, branch off main, commit, push, and open a pull request, plus fork vs clone, syncing a fork with upstream, fixing 'remote origin already exists', and moving commits as patch files with git format-patch and git am.