Git Undo Tutorial
Overview
In Git, undoing changes can mean several different things: undoing local changes, undoing commits, or undoing pushed commits. This document will cover various ways to undo changes in Git with examples.
Table of Contents
- Undoing Unstaged Changes
- Undoing Staged Changes
- Undoing Commits
- Undoing Pushed Commits
- Undoing Changes in a Specific File
- Undoing Merge Commits
- Useful Tips
Undoing Unstaged Changes
To discard changes in the working directory (unstaged changes), use:
Example
This will revert the changes in README.md
to the last committed state.
Undoing Staged Changes
To unstage changes that have been added to the staging area, use:
Example
This will unstage README.md
, but keep the changes in the working directory.
Undoing Commits
Undo Last Commit
To undo the last commit but keep the changes in the working directory, use:
Example
This will undo the last commit but keep your changes staged.
To undo the last commit and discard the changes, use:
Example
This will undo the last commit and discard the changes.
Undo Multiple Commits
To undo multiple commits, specify the number of commits to go back:
Example
This will undo the last three commits and discard the changes.
Undoing Pushed Commits
To undo pushed commits, you can use git revert
to create new commits that undo the changes:
Example
This will create a new commit that undoes the changes introduced by commit 1a2b3c4d
.
To remove the commits entirely, you can force push after resetting:
Example
This will remove the last two commits and force push the changes to the main
branch.
Undoing Changes in a Specific File
To undo changes in a specific file to a particular commit, use:
Example
This will revert README.md
to its state in the previous commit.
Undoing Merge Commits
To undo a merge commit and keep the changes, use:
Example
This will revert the merge commit 1a2b3c4d
.
To undo a merge commit and discard the changes, use:
Example
This will reset the branch to the state before the merge commit.
Useful Tips
- Backup Important Changes: Before using commands that modify commit history or discard changes, ensure that you have backups of important work.
- Check Status: Use
git status
to review the current state of your working directory and staging area before making changes. - Use Interactive Rebase: For more granular control over commit history, consider using
git rebase -i
.
Summary
Undoing changes in Git can range from discarding local changes to modifying commit history. By understanding and using the appropriate commands, you can manage your repository effectively and maintain a clean commit history.