Black Friday sale: 30% off Pro and Unlimited, until 22 December

How to undo a Git commit you already pushed

Use git revert to undo a change on a shared branch and keep the history your teammates already have.

You pushed a change to a shared branch, and your teammates may already have it. Use git revert to add a commit that reverses the change while keeping the original commit in the branch’s history. If the commit is still local, see how to undo it before you push.

Find the commit on the shared branch

Start at the root of your repository. This example uses main on origin. Substitute your shared branch and remote, and pick a branch name and directory that are both new. A fresh worktree keeps the revert away from local edits and ignored files in your usual checkout.

git fetch --no-prune \
  --no-prune-tags origin main &&
git worktree add \
  -b revert-coupon \
  ../web-revert FETCH_HEAD &&
cd ../web-revert

FETCH_HEAD here is the tip of the branch you just fetched. Once the commands succeed, stay in web-revert for the remaining steps. List the recent commits.

git log -8 --oneline
c1aee77 Fix cart rounding
884500d Turn coupons on
ba6741a Add checkout banner

Copy the ID of the commit you want to undo. In this example it is 884500d, even though another commit came after it. Read the patch to check that you have the right change.

git show 884500d

These steps are for a regular, single-parent commit. Reverting a merge commit requires choosing which parent to keep as the baseline.

Revert it and check the diff

Run the revert in the fresh worktree before building or copying files into it.

git revert --no-edit 884500d

If Git stops with a conflict, resolve the files, stage them, and run git revert --continue. To return the new branch to its pre-revert state, run git revert --abort.

Once the revert succeeds, compare the new commit with its parent.

git diff HEAD^ HEAD

The diff for banner.txt shows the reversal.

-Coupons on
+Coupons off

The revert turns coupons off again. The later cart rounding change stays in place. Run the checks you would run for any change to these files.

Publish through your team’s review

Push the new branch and open a pull or merge request with the shared branch as its target.

git push -u origin revert-coupon

Check the request’s target and diff before merging. Follow the same reviews and checks as any other change. If that branch also deploys, see how to prevent accidental pushes to production.

Check the patch before your next push

On a Mac, push& (Pushand) lets you preview the outgoing diff before you send the branch.

More Git how-tos