I make new branch from master
with:
git checkout -b testbranch
I make 20 commits into it.
Now I want to squash those 20 commits. I do that with:
git rebase -i HEAD~20
What about if I don't know how many commits? Is there any way to do something like:
git rebase -i all on this branch
Git's squash commits command There is no explicit Git squash command. Instead, to squash git commits, the interactive git rebase is used. To squash all commits on a single branch, the interactive git rebase command must be passed one of two arguments: the id of the commit from which the branch split from its parent.
Squashing by Merging With the –squash Option This can effectively clean the commit-graph in a branch. However, we sometimes make many commits in our feature branch while working on it. After we've developed the feature, we usually want to merge the feature branch to the main branch, say “master”.
Another way to squash all your commits is to reset the index to master:
git checkout yourBranch git reset $(git merge-base master $(git branch --show-current)) git add -A git commit -m "one commit on yourBranch"
This isn't perfect as it implies you know from which branch "yourBranch" is coming from.
Note: finding that origin branch isn't easy/possible with Git (the visual way is often the easiest, as seen here).
Note: git branch --show-current
has been introduced with Git 2.22 (Q1 20219).
EDIT: you will need to use git push --force
Karlotcha Hoa adds in the comments:
For the reset, you can do
git reset $(git merge-base master $(git rev-parse --abbrev-ref HEAD))
[That] automatically uses the branch you are currently on.
And if you use that, you can also use an alias, as the command doesn't rely on the branch name.
sschoof adds in the comments:
Since my default branch is called
main
and my search had multi times brought me here:
To copy it for my next timegit reset $(git merge-base main $(git rev-parse --abbrev-ref HEAD))
Checkout the branch for which you would like to squash all the commits into one commit. Let's say it's called feature_branch
.
git checkout feature_branch
Do a soft reset of your origin/feature_branch
with your local main
branch (depending on your needs, you can reset with origin/main as well). This will reset all the extra commits in your feature_branch
, but without changing any of your file changes locally.
git reset --soft main
Add all of the changes in your git repo directory, to the new commit that is going to be created. And commit the same with a message.
# Add files for the commit. git add ... git commit -m "commit message goes here"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With