Git provides multiple ways to undo commits based on your workflow and repository state.
- Revert changes safely using git revert.
- Modify commit history using git reset.
Reasons for Reverting a Git Commit
To safely undo unwanted changes while keeping the commit history clear and reliable.
- Fix Mistakes: If a commit introduces a bug or an error, reverting it can help fix the issue.
- Undo Changes: If changes are no longer needed or were made accidentally, reverting can remove them from the history.
- Maintain History: Reverting commits preserves project history for tracking and collaboration.
Reverting a Git Commit
Git allows you to review project history, fix mistakes, and undo changes using various related commands.
Step 1: git log
Before reverting a Git Commit, list all commits to identify the target commit hash using the command below.
git logStep 2: git revert
git revert creates a new commit that safely undoes a previous commit without changing branch history.
git revert <commit_hash>Change your commit hash with the "<commit_hash>"

git revert options:
- -e or --edit: This option lets you edit the commit message prior to committing the revert. It is the default option.
- --no-edit: Using this option will not start committing the text editor.
- -n or --no-commit: This option applies inverse changes to the index and working tree without creating a new commit.
Resetting Commits
Moves the current HEAD to a specified state. Less commonly used due to its destructive nature.
git resetThis git command is not commonly used to its restrictive use. It has three basic options namely:
- --soft : Moves HEAD to the specified commit and keeps changes staged.
- --hard : Moves HEAD and discards all changes in both the staging area and working directory.
- --mixed : Moves HEAD and unstages changes but keeps them in the working directory (default).
Removing Files from Repository
Removes tracked files from the index and/or working tree.
git rm- It cannot remove files just from the working directory.
- The files removed must be identical to those in the current head.
git rm options:
- (files) ... : Specifies one or more files to remove.
- -f / --force : Forces removal by overriding up-to-date checks between HEAD, staging area, and working directory.
- -n / --dry-run : Shows which files would be removed without actually deleting them.
- -r : Allows recursive removal when a directory is specified.
- -- : Separates command options from filenames to avoid misinterpretation.
- -q / --quiet : Suppresses output messages.
- --cached : Removes files only from the staging index, leaving the working directory unchanged.