Home > Software design >  How to revert last(latest) commit on my feature branch(Remote) in git
How to revert last(latest) commit on my feature branch(Remote) in git

Time:11-15

I have pushed 2 commits in my feature branch(remote) but now I have to revert back the latest commit for the branch.

e.g commit A latest commit B first

here I want to delete commit A and want to leave changes as it was in commit B

I can see many solution in google but not sure what to do? Some says make the changes and again push the changes in remote. Some says to delete the last commit and rewrite the history.

I don't want to loose the changes from the first commit. and just want to delete the latest commit from remote branch.

CodePudding user response:

One easy approach is to create a new commit cancelling the changes of commit A, using the git revert operation.

This method has the advantage of not altering the commit history, which makes it straightforward for other users to pull the feature branch.

  • In your local repository, execute the following:
git revert <sha-of-commit-A>
  • Enter a commit message like "undo changes of commit-A"
  • Then push the feature branch to the remote.

The feature branch will then only contain the changes of commit-B.

Reference article with more details.

CodePudding user response:

Note: I recommend Mehdi's answer as it is the safer approach, but I will keep my answer in case your preference is to remove the reverted commit from history.

This should be relatively straightforward, follow these steps (I will assume that the local feature branch is called localFeatureBranch):-

1- Create a local backup of your feature branch (in case things go wrong):-

git checkout localFeatureBranch
git branch localFeatureBranchBackup

2- Now that you have a backup, delete the latest commit (it would be good to ensure first that you don't have any changes that need to be committed):-

git reset --hard HEAD~1

The above will completely delete the last commit as well as any staged/unstaged changes, so please be careful when using the above command. A more forgiving command would be git reset --soft HEAD~1, but then you have to go to files one by one and unstage them/revert them.

3- Now force push your changes to the remote branch:-

git push origin localFeatureBranch --force

Force pushing a branch is not always recommended especially if there are multiple people working on the same remote branch, but if you are the only one working on this branch and you have already backed it up locally (which you should have in step 1), then it should be a harmless exercise.

  • Related