Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine git commits

Tags:

git

In my local GIT repository, I have the following commits:

A --> B --> C --> D

(Where D is the head)

I would like to combine/squash B and C into a single commit. How could I do that?

Thanks.

like image 379
Anas Mughal Avatar asked Feb 20 '23 10:02

Anas Mughal


1 Answers

Use this command:

git rebase -i A ;# where A is A's commit hash

In the interactive editor, change the the lines, which should look something like this:

pick c7787af A
pick f9d9262 B
pick 6c363d0 C
pick 40f657d D

To this:

pick c7787af A
pick f9d9262 B
squash 6c363d0 C
pick 40f657d D

If you'd prefer to abandon C's commit message, but still squash the commit, use this:

pick c7787af A
pick f9d9262 B
fixup 6c363d0 C
pick 40f657d D

Never rebase a branch you've already shared with collaborators. The action changes SHA1 hashes, and results in non-fast-forward updates.

As Jason noted in comments, an alternative syntax is git rebase -i HEAD~4. When you're rebasing recent history to squash commits (i.e. when it's easy to count parents back in time), this avoids the trouble of looking up A's hash.

like image 175
Christopher Avatar answered Feb 27 '23 21:02

Christopher