Search code examples
gitversion-controlgit-squashgit-amend

How do I find all commits with a certain message and squash them into the previous commit?


When I've been coding I often use git commit -am <message> to save my work, and occasionally I'll use git commit --amend if I made a mistake in the previous commit. Recently I thought I was being clever and started combining them doing git commit -am --amend. Today I looked at my git log and I'm greeted with random tiny commits with the message --amend. I understand my mistake now: --amend is being interpreted as the message.

Fortunately it doesn't look like there's multiple of these stacked together, so all I need to do is something like for each commit with '--amend', squash into previous commit.

Is there a way I can do this?

As an example from my git log:

* commit f9d69146e47823d6cdc5e0856257b5f63518268d
| Author: Batman <[email protected]>
| Date:   Mon Aug 5 19:18:21 2019 -0400
| 
|     --amend
| 
* commit b07d42e8802dddc144a795471f789b7eb1475ccb
| Author: Batman <[email protected]>
| Date:   Mon Aug 5 19:07:47 2019 -0400
| 
|     Some key feature that allows user to use product
| 

Solution

  • you might use sed or awk for this to manipulate the "rebase script file". We basically reuse this answer:

    How do I run git rebase --interactive in non-interactive manner?

    The manipulation script should look something like this (ATTENTION! untested):

    #!/usr/bin
    sed -i  's/pick \(.*\) --amend/squash \1 --amend/g' $1