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.
git restore file.txtgit checkout -- <file> (aging option)
Does the same thing, but is considered less preferred.
git checkout -- file.txt2. 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.
git restore --staged file.txtgit reset <file>
An alternative way to remove a file from the index.
git reset file.txt3. Undoing a commit while changing history
git reset
Used to roll back local commits.
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 changesChanges 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.
git revert HEADSafe for shared branches.
5. Temporarily undoing changes
git stash
Temporarily saves changes and clears the working tree.
git stash
git stash popKey phrasing for an interview
Undoing changes in Git uses the
restore,reset,revert, andstashcommands. The specific command is chosen depending on where the changes are: the working tree, the staging area, or the commit history.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.