MadPhysicist
MadPhysicist

Reputation: 5841

Git Remove Last Commit When HEAD Is on Previous Commit

In a somewhat long-winded sequence of events caused by local, test and development repositories going out of sync, I ended up making some commits which now need to be deleted.

In particular, the latest commit, call it A is the one that needs to be deleted. Commit that precedes it, call it B is the one on which the HEAD is located.

When I run git status I get

Not currently on any branch. nothing to commit (working directory clean)

How can I get rid of the commit A? Also, will getting rid of it automatically make Git realize that it is on the master branch?

Upvotes: 0

Views: 112

Answers (3)

Bryce Drew
Bryce Drew

Reputation: 6759

Easy method:

git branch -f master

Correct method:

git checkout master
git reset --hard HEAD~1

See How to revert Git repository to a previous commit?

Also: If head is on the previous commit, then your master branch is not checked out. Your head is detached.

Explanation:

D <- master
C <- head
B
A

If you have checked out C, you just force master to C.

If you have checked out D, you just revert master to C.

Upvotes: 1

sanjeevjha
sanjeevjha

Reputation: 1549

step 1: you need to list down all the git branch you have

git branch

step 2: you need to checkout to particular branch from the list and make sure you should checkout to that branch only where you want to delete particular commit

git checkout branch_name

step 3: now you need to list down all the commits to that branch

git log

setp 4: now you need to select the commit id that you want to delete from the list

step 5: now you need to execute the command to delete particular commit. here below branch_name is same where currently you are

git revert commit_id

git push origin branch_name

step 6: now if you execute git log then you find there is new commit happen and in this commit code is delete that you want to do. Now if you go to code base then find unwanted code is removed

I hope it will help you out.

Thanks.

Upvotes: 1

sanjeevjha
sanjeevjha

Reputation: 1549

If you want to delete any commit execute below commands

step1: git revert commit_id

step:2 git push origin branch_name

Upvotes: 1

Related Questions