0

I have a branch(mybranch) with 6 commits. After 6 commits I want to revert the last 3 commits. So I checked out sha using git checkout 3978bf85d8a05653c927cfabdf8c018167faf363 I can see last 3 commits are reverted. Now I want to update mybranch with this. How can I do that?

(hase) root@ajain1:~/hase# git status
HEAD detached at 3978bf8
nothing to commit, working directory clean
codec
  • 7,978
  • 26
  • 71
  • 127
  • 1
    `HEAD` is just a pointer, not a real branch. You haven't reverted anything; you've just pointed at something that isn't a branch. – chepner Jun 21 '19 at 01:14

3 Answers3

4

If you want to 'force' a particular branch to point to a specific commit/ID, you can simply do:

git checkout mybranch
git reset --hard 3978bf8

And it will update mybranch to point directly to that commit.

Craig Otis
  • 31,257
  • 32
  • 136
  • 234
  • It did, but unable to push ` ! [rejected] mybranch -> mybranch (non-fast-forward)` – codec Jun 21 '19 at 01:02
  • 1
    Are you trying to push to a repository that _other people_ have access to? If so, you should probably reconsider what you're doing - a "force push" is rarely recommended when used against a public repository. If this is a private repository/fork that only you access, you can force the push using: `git push -f ` – Craig Otis Jun 21 '19 at 01:03
1

You might find this answer helpful which explains that new commits should be added to revert the previous commits in order to preserve the branch's history.

One way to do this is to call $ git revert --no-commit commitHash on the 3 commits to be reverted, and then call $ git commit -m "the commit message".

An alternate solution is to checkout the contents of the last commit (let's call it A) you don't want to revert, and then commit this state which can be done with $ git checkout -f A -- followed by $ git commit -a

AbsoluteSpace
  • 710
  • 2
  • 11
  • 21
1

As your HEAD is detached and currently pointing to commit 3978bf8, you can create new branch at the commit. You can merge this branch to your branch mybranch.

git branch new_branch_name
git checkout mybranch 
git merge new_branch_name
Venkataraman R
  • 12,181
  • 2
  • 31
  • 58