乐闻世界logo
搜索文章和话题

How do i squash my last n commits together in git?

4个答案

1
2
3
4

Git rebase can easily accomplish this without the need for git merge --squash. In this example, we will squash the last three commits.

If you want to start with a new commit message from scratch, this is sufficient:

shell
git reset --soft HEAD~3 git commit

If you want to edit a new commit message combined with the existing commit messages (i.e., similar to the pick/squash/squash/…/squash sequence in the git rebase -i interactive command), you need to extract these messages and commit them with git commit:

shell
git reset --soft HEAD~3 && git commit --edit -m"$(git log --format=%B --reverse HEAD..HEAD@{1})"

Both methods squash the last three commits into a single new commit in the same way. A soft reset simply moves HEAD to the last commit you do not want to squash. A soft reset does not touch the index or working tree, leaving the index in the state required for the new commit (i.e., it already contains all the changes from the commits you are discarding).

2024年6月29日 12:07 回复

I recommend avoiding git reset as much as possible, especially for Git beginners. Unless you genuinely need to automate a process based on multiple commits, there's a straightforward method...

  1. Place the commits to be squashed on the working branch (if not already done) — use gitk for this.
  2. Inspect the target branch (e.g., 'master').
  3. Run git merge --squash <working-branch-name>.
  4. Then run git commit.

The commit message will be pre-filled based on the squash.

2024年6月29日 12:07 回复

A straightforward solution without rebase:

shell
git reset --soft HEAD~2 git commit -m "new commit message" git push -f

where 2 indicates that the last two commits will be squashed, and you can replace it with any number.

2024年6月29日 12:07 回复

You can use git merge --squash instead of git rebase -i. Assume you are on the master branch and want to squash the last 12 commits into one.

Warning: First, ensure your work is committed – check that git status shows a clean working directory (because git reset --hard will discard both staged and unstaged changes).

Then:

shell
# Reset the current branch to the commit just before the last 12: git reset --hard HEAD~12 # HEAD@{1} represents the state of the branch just before the previous command. # This command sets the index state as it would be immediately after merging from that commit: git merge --squash HEAD@{1} # Commit the squashed changes. The commit message will be prepopulated with the messages of all squashed commits: git commit
2024年6月29日 12:07 回复

你的答案