Basically I have the scenario that I have a commit on the master
which I want to revert to the previous state to commit new changes.
The whole thing should be done in a branch, so my idea was to branch the master with the unwanted commit to a new branch b
, then revert the unwanted commit unwantedC
in my branch b
and push it as a new commit revertedUnwantedC
. My goal ist that I don't get a status like "your branch is xy commits behind master", because my branch should be ahead then. If that is possible I want to push my desired changes newCommit
in the branch and then make a PR that doesn't complain about merge problems with the master because he thinks that the master is ahead. Is something like that possible ? And what commands would I have to use?

- 117
- 9
2 Answers
Yes, what you describe should be easily possible. Consider the following history:
A-B-C-D-E <- master
Now, C
is the faulty commit that you want to revert (and then further build upon that reverted state):
$ git checkout -b unwanted C
You are now on a new branch called unwanted
which contains your faulty commit and everything before (but not everything after).
A-B-C-D-E <- master
^-- unwanted
Now, revert C (will create a new commit on your branch) and keep working:
$ git revert C
# hack hack hack
$ git commit
# hack hack hack
$ git commit
gives you (C'
being the revert of commit C
):
A-B-C-D-E <- master
\
C'-X-Y <- unwanted
You can then push and create a pull request/merge request or simply merge unwanted
back into master
:
$ git checkout master
$ git merge unwanted
Note that after the merge any changes of C
will no longer exist in master (they have been reverted and merging also merges these reverse changes).

- 246,190
- 53
- 318
- 364
-
Thank for you reply, i tried what you wrote, but once i try to revert the unwanted `c` i face the problem that the commit is a merge commit and `is a merge but no -m option was given.` can you explain what i would have to do ? Tbh i don't get what the mainline (-m) switch is doing – scholl123 May 08 '20 at 14:43
-
1The mainline switch tells Git which side of a merge to keep and which to discard. When you have a commit "Merge branch B into master" then running `git revert -m 1` will revert changes of `B` and keep `master`. Passing `-m 2` will revert changes of `master` and keep `B`. Read [How to revert a faulty merge](https://github.com/git/git/blob/master/Documentation/howto/revert-a-faulty-merge.txt) in the Git documentation for more details. – knittl May 08 '20 at 15:07
You can use the git revert command to create a new commit that undoes a previous commit. This StackOverflow question goes into more detail on how it works.
When you merge your branch with the new commit back into master
you'll have one commit that makes the change and another commit that undoes that change.

- 1,502
- 2
- 23
- 37