Unstage a file or discard my edits

destructive beginner #restore#unstage#discard#clean

When to use this: You staged something by mistake, or you want to throw away edits and return a file to its last committed state.

Destructive: this can lose work. Discarding edits cannot be undone: uncommitted work is not recoverable. Unstaging is safe.

Before you start

Steps

  1. Unstage (safe: keeps your edits)

    terminal
    git restore --staged src/pages/index.astro

    Moves the file back from 'staged' to 'modified'. Nothing is lost.

  2. Discard edits to one file (DESTRUCTIVE)

    terminal
    git restore src/pages/index.astro

    Resets the file to the last commit. Your edits in it are gone for good.

  3. Discard everything uncommitted (DESTRUCTIVE)

    terminal
    git restore .

    Reverts all tracked files. New untracked files stay.

  4. Preview removal of untracked files

    terminal
    git clean -nd

    -n is a dry run: lists new files and folders Git would delete. Nothing is removed.

  5. Delete untracked files (DESTRUCTIVE)

    terminal
    git clean -fd

    Actually deletes the files listed by the dry run. Add -x only if you also want ignored files removed (it will delete node_modules and .env).

How to verify it worked

  • git status shows a clean tree, or only what you meant to keep.

How to undo it

Unstaging: stage again with git add <file>. Discarded edits: not recoverable by Git. Check your editor's local history or the Recycle Bin.

Common errors and fixes

error: pathspec '...' did not match any file(s) Check the path and spelling. Run git status to copy it.

Q&A

How do I keep my edits but get them out of the way?

Stash them: git stash push -u. They can come back with git stash pop.

Why always run git clean -nd first?

clean removes files Git cannot restore. The dry run shows the list so you do not delete something important.

Practice these as flashcards →

Terms in this scenario

Related scenarios

My notes

Saved in this browser only.