Skip to main content

Which Git commands are used to undo changes?

Undoing changes in Git uses several commands, and the choice depends on the stage the changes are at.


1. Undoing changes in the working tree (before git add)

git restore <file>

Undoes changes in a file and returns it to the state of the last commit.

bash
git restore file.txt

git checkout -- <file> (aging option)

Does the same thing, but is considered less preferred.

bash
git checkout -- file.txt

2. Undoing a staging area addition (unstage)

git restore --staged <file>

Removes the file from the staging area, but keeps the changes in the working tree.

bash
git restore --staged file.txt

git reset <file>

An alternative way to remove a file from the index.

bash
git reset file.txt

3. Undoing a commit while changing history

git reset

Used to roll back local commits.

bash
git reset --soft HEAD~1 # undo the commit, keep the changes staged git reset --mixed HEAD~1 # undo the commit, keep the changes in the working directory git reset --hard HEAD~1 # completely remove the commit and the changes

Changes history, dangerous for public branches.


4. Undoing a commit without changing history

git revert

Creates a new commit that undoes the changes of the specified commit.

bash
git revert HEAD

Safe for shared branches.


5. Temporarily undoing changes

git stash

Temporarily saves changes and clears the working tree.

bash
git stash git stash pop

Key phrasing for an interview

Undoing changes in Git uses the restore, reset, revert, and stash commands. The specific command is chosen depending on where the changes are: the working tree, the staging area, or the commit history.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.