1

I realized that I had to create a branch first, but already did 2 commits. Okay, I found this post Branch from a previous commit using Git and created a new branch from a prev-prev commit using this command:

git checkout -b branch-name commit-id
git push origin branch-name

But when I looked back in GitHub I saw the master still has 2 last commits (that I wanted them to be only in a branch).

What should I do to get rid of them in the master but still keep them in the branch?

UPD Found this solution.

  1. Reverted to the previous commit git reset --hard commit
  2. Pushed with force git push --force origin master
mimic
  • 4,897
  • 7
  • 54
  • 93
  • Master is already a branch which was created when you initialized git in your project I guess. As far as I know you are allways committing to a branch. – Luckyfella Oct 22 '21 at 23:07
  • 1
    reverting commits on any branch is a common task. Move that commits to another branch could be tedious. Are you open to a non-elegant way? The elegant way is https://stackoverflow.com/questions/1628563/move-the-most-recent-commits-to-a-new-branch-with-git – JRichardsz Oct 22 '21 at 23:58
  • @JRichardsz Hah I'm open to any way. I already found some way (see the update), wonder if your's is different or not. Thanks! – mimic Oct 23 '21 at 03:14
  • 1
    Watch out for the word "revert" in Git, which usually refers to the `git revert` command, not the `git reset` command. Revert as an English-language verb tends to mean more what `git reset` *does*, which means Git kind of assigned the wrong verb to the action (Mercurial uses `backout` where Git uses `revert`, which is a point in favor of Mercurial). Anyway, your solution (reset and force-push) is the right one for your case, it's just that this isn't *called* "reverting" in Git. – torek Oct 23 '21 at 03:27
  • @torek Thanks for explaining, I didn't know that! – mimic Oct 23 '21 at 03:36
  • with your approach, just the master is update. What about the 2 commits? Didn't you need them in another branch? – JRichardsz Oct 23 '21 at 05:33
  • @JRichardsz It's already there (see the beginning of my post) when I did the branching from the commit, they went to that branch. – mimic Oct 23 '21 at 22:07

1 Answers1

1

"Reverting" is not the right term, but what you did was effective:

git switch master
git reset --hard <past_commit>

Or, shorter, using git switch -C

git switch -C master <past_commit>

Then:

git push --force

Assuming you are the only one working on that repository, that will reset the remote (GitHub) branch to what you want.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • `git branch -f master thatcommit` skips the worktree churn of the switch/hard reset. – jthill Oct 24 '21 at 00:31
  • @jthill I agree. I have edited the answer to propose the alternative `git switch -C`, which does include a `git branch -t`/`git switch` combo. – VonC Oct 24 '21 at 02:03