Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to git commit --amend a commit that's the base of a branch

I have branch foo off of master/head. I wanted to ammend the master/head and have these changes picked up on branch foo. I did the following:

git checkout master
git add ...
git commit --amend
git checkout foo
git rebase master

The problem was the old non-amended commit shows up as part of branch foo after the amend, and it got rebased onto master. I did a git rebase -i and deleted the old commit and that worked, but is there an easier/safer way to modify the commit that's the base of a branch? And yes, it's all local commits that haven't been pushed..

like image 599
Aaron Avatar asked Aug 08 '12 00:08

Aaron


People also ask

How do you commit amend a specific commit?

You can modify the most recent commit in the same branch by running git commit --amend. This command is convenient for adding new or updated files to the previous commit. It is also a simple way to edit or add comments to the previous commit. Use git commit --amend to modify the most recent commit.

Can you amend someone else's commit?

There is no "right" way to amend a commit that's been pushed. Amending a commit is the same as rebasing.


1 Answers

All you needed to do was to tell git where to start the rebase from: You can do this

git rebase --onto master SOMESHA foo

Where SOMESHA is the old master SHA. That is if your tree now looks like this

* aaaaaa - (master)
| * bbbbbb - (foo)
| * cccccc - (old master)
|/  
* ffffff

And you do

git rebase --onto master cccccc foo

Your tree will then look like this.

* dddddd - (foo)
|
* aaaaaa - (master)
|
* ffffff

ASIDE: we can use different names for the cccccc commit if you dont like using SHA values.

> git reflog master

aaaaaa master@{0}: reset: moving to something
cccccc master@{1}: commit: change the froozle
ffffff master@{2}: commit: snarf the froozle 

This means we can reference cccccc as master@{1} (AKA, the previous location of master)

So we could write this rebase as

git rebase --onto master master@{1} foo

Another description of the commit cccccc is foo^ (AKA, the parernt commit for foo), so we could also write this as

git rebase --onto master foo^ foo

They all do exactly the same thing, and you may prefer to use different ones in different situations. I usually find the SHA simple to use, as I will often pull up a graph of my repository before performing this kind of operation.

like image 120
Michael Anderson Avatar answered Sep 20 '22 05:09

Michael Anderson