stefana
stefana

Reputation: 2626

Remove pushed commits from Git

I have the following history in my branch.

I want to remove commit 2 and 3 from the history. So that commit 1 is the latest. I am the only person using this repository.

I am using SourceTree and in the Terminal I entered the following:

git rebase -i

Then I get a colorful screen where I can't enter commands. What can I do?

EDIT:

push error

ssh: connect to host <myhost> port 22: Bad file number
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Upvotes: 4

Views: 1498

Answers (4)

Mike Monkiewicz
Mike Monkiewicz

Reputation: 4709

All these answers seem to show how to remove commit2 & commit3 from your local repository, but do not address the remote repository.

First, exit the interactive rebase you are in. That only affects local history. You might need to exit the text editor you are in or run git rebase --abort. I'm not quite sure of your exact state.

Once you are back to your normal command line, checkout master since it is already at the desired commit1.

git checkout master

Then force origin/master to update to master.

git push -f

As a warning to other readers, never do a forced push on a shared repository with other developers! This works for the original poster because they are the only one using their remote repository.

Upvotes: 2

Lalit Sachdeva
Lalit Sachdeva

Reputation: 6619

If you want to commit on top of the current HEAD with the exact state at a different commit, undoing all the intermediate commits, then you can use reset to create the correct state of the index to make the commit.

# reset the index to the desired tree
git reset 56e05fced

# move the branch pointer back to the previous HEAD
git reset --soft HEAD@{1}

git commit -m "Revert to 56e05fced"

# Update working copy to reflect the new commit
git reset --hard

Upvotes: 0

user2699113
user2699113

Reputation: 4509

You can do revert on those two commits: 2 and 3:

git revert "commit 3"
git revert "commit 2"

or git reset:

git reset --hard "commit 1"

Upvotes: 0

kgautron
kgautron

Reputation: 8263

If you want to cancel the commits but keep the modifications you made in the files :

git reset --soft HEAD^2

If you want to both cancel the commits AND cancel the modifications in your local files :

git reset --hard HEAD^2

Head^X means the Xth commit before last commit on the current branch.

Upvotes: 2

Related Questions