Junior
How to combine multiple commits into one using Git?
sobes.tech AI
Answer from AI
To squash multiple commits into one using Git, the command git rebase -i <commit-ish> is used.
- Identify the commit before which you want to squash. This can be a commit hash, branch, or tag.
- Run the command
git rebase -i <commit-ish>. For example, to squash the last 3 commits:git rebase -i HEAD~3 - A text editor will open with a list of commits. The first commit in the list (top) should have the word
pick. The other commits you want to squash with the first should be changed frompicktosquashors.pick abcd123 Initial commit squash efgh456 Feature A part 1 squash ijkl789 Feature A part 2 - Save and close the editor.
- A new editor will open to create a commit message. Combine or edit the commit messages as you see fit to create a meaningful message for the new squashed commit.
// Message for the new combined commit // This is a combination of 3 commits. // Initial commit // Feature A part 1 // Feature A part 2 - Save and close the editor. Git will perform the squash.
If the branch you are working on has already been pushed to a remote repository, you will need to force push with the -f or --force-with-lease flag.
git push origin <your_branch> -f
This is necessary because the commit history has been rewritten. Force pushing can be dangerous if other developers are working on this branch. Always verify if force pushing is acceptable.
Alternatively, you can use the --fixup and --autosquash flags during commits, then run git rebase -i --autosquash <commit-ish> for automatic squashing.