Categories
Coding

How to Undo a Commit Before Push in Git

Method 1: Amend the Commit (Simple Changes)

Use Case: Fix a typo in the commit message or quickly add a small file you forgot in the original commit.

How to:

1. git commit --amend This opens your editor to change the message if you want that.

2. Make the fixes you wanted to your files or if needed.

3. Stage your changes with git add .

4. Close the editor because this finalizes the amended commit.

Method 2: Reset Your Branch (More Rewriting)

Use Case: You want to remove the last commit or even several commits from your local branch history.

Types of reset:

git reset --soft HEAD~1: Undo the commit, but keep changes in your working directory and staging area.

git reset --mixed HEAD~1: Undo the commit, changes remain in your working directory (unstaged).

git reset --hard HEAD~1: Undo the commit and discard all changes since then.

Method 3: Revert the Commit (Preserve History)

Use Case: You want to create a brand new commit that effectively “undoes” the changes in the previous commit but keep the original commit in your history.

How to:

git revert <commit-hash> Use git log to find the hash of the commit you want to revert.

Important Things

Don’t Undo Pushed Commits: The methods that I wrote here assume the commit hasn’t been pushed. Rewriting history after pushing will cause problems for collaborators.

Before You Start: If you’re not sure which method to use the safest way is to create a new branch as a backup before making changes.

Example Scenario

Let’s say you committed a change you want to refine before pushing.

1. Stash Unrelated Work (which is optional): If you have other uncommitted changes, git stash will temporarily save them.

2. Use Reset (depending on the extent of change):

  • Small amends: git commit --amend
  • Rewriting needed: git reset --soft HEAD~1

3. Make Changes and Re Commit: Refine your code then stage and create a new commit.

Leave a Reply

Your email address will not be published. Required fields are marked *