How can I squash my last X commits together into one commit using Git?
-
4Related: Git - combining multiple commits before pushing. – user456814 Jun 6 '14 at 8:07
-
3@matt TortoiseGit is your tool. It provides a single function "Combine to one commit" which will call all steps automatically in the background. Unfortunately only available for Windows. See my answer below. – Matthias M Nov 6 '15 at 12:57
-
2For squashing upto THE first commit see this - stackoverflow.com/questions/1657017/… – goelakash Mar 6 '16 at 13:26
-
2post squash one need to do force push stackoverflow.com/questions/10298291/… – vikramvi Jul 14 '16 at 13:04
-
1In addition to the posted answers, GUI clients can do this easily. I can squash dozens of commits in GitKraken with only four clicks. – Aaron Franke Jan 14 '19 at 12:56
Use git rebase -i <after-this-commit>
and replace "pick" on the second and subsequent commits with "squash" or "fixup", as described in the manual.
In this example, <after-this-commit>
is either the SHA1 hash or the relative location from the HEAD of the current branch from which commits are analyzed for the rebase command. For example, if the user wishes to view 5 commits from the current HEAD in the past the command is git rebase -i HEAD~5
.
-
291This, I think, answers this question a bit better stackoverflow.com/a/5201642/295797 – Roy Truelove May 1 '13 at 14:22
-
111
-
49
<after-this-commit>
is commit X+1 i.e. parent of the oldest commit you want to squash. – joozek Nov 4 '14 at 12:04 -
61The difference between this
rebase -i
approach andreset --soft
is,rebase -i
allows me to retain the commit author, whilereset --soft
allows me to recommit. Sometimes i need to squash commits of pull requests yet maintaining the author information. Sometimes i need to reset soft on my own commits. Upvotes to both great answers anyways. – zionyx Sep 15 '15 at 9:31 -
25
Use git rebase -i <after-this-commit> and replace "pick" on the second and subsequent commits with "squash" or "fixup", as described in the manual.
uhhhh... wut? – Cheeso Jul 27 '16 at 3:18
You can do this fairly easily without git rebase
or git merge --squash
. In this example, we'll squash the last 3 commits.
If you want to write the new commit message from scratch, this suffices:
git reset --soft HEAD~3 &&
git commit
If you want to start editing the new commit message with a concatenation of the existing commit messages (i.e. similar to what a pick/squash/squash/…/squash git rebase -i
instruction list would start you with), then you need to extract those messages and pass them to git commit
:
git reset --soft HEAD~3 &&
git commit --edit -m"$(git log --format=%B --reverse HEAD..HEAD@{1})"
Both of those methods squash the last three commits into a single new commit in the same way. The soft reset just re-points HEAD to the last commit that you do not want to squash. Neither the index nor the working tree are touched by the soft reset, leaving the index in the desired state for your new commit (i.e. it already has all the changes from the commits that you are about to “throw away”).
-
187Ha! I like this method. It is the one closes to the spirit of the problem. It's a pity that it requires so much voodoo. Something like this should be added to one of the basic commands. Possibly
git rebase --squash-recent
, or evengit commit --amend-many
. – Adrian Ratnapala Nov 8 '13 at 17:50 -
13@A-B-B: If your branch has an “upstream” set, then you may be able to use
branch@{upstream}
(or just@{upstream}
for the current branch; in both cases, the last part can be abbreviated to@{u}
; see gitrevisions). This may differ from your “last pushed commit” (e.g. if someone else pushed something that built atop your most recent push and then you fetched that), but seems like it might be close to what you want. – Chris Johnsen Apr 23 '14 at 6:13 -
115This kinda-sorta required me to
push -f
but otherwise it was lovely, thanks. – 2rs2ts Oct 29 '14 at 23:32 -
45@2rs2ts git push -f sound dangerous. Take care to only squash local commits. Never touch pushed commits! – Matthias M Sep 24 '15 at 14:49
-
23I also need to use
git push --force
afterwards so that it takes the commit – Zach Saucier Jul 21 '16 at 0:21
You can use git merge --squash
for this, which is slightly more elegant than git rebase -i
. Suppose you're on master and you want to squash the last 12 commits into one.
WARNING: First make sure you commit your work—check that git status
is clean (since git reset --hard
will throw away staged and unstaged changes)
Then:
# Reset the current branch to the commit just before the last 12:
git reset --hard HEAD~12
# HEAD@{1} is where the branch was just before the previous command.
# This command sets the state of the index to be as it would just
# after a merge from that commit:
git merge --squash HEAD@{1}
# Commit those squashed changes. The commit message will be helpfully
# prepopulated with the commit messages of all the squashed commits:
git commit
The documentation for git merge
describes the --squash
option in more detail.
Update: the only real advantage of this method over the simpler git reset --soft HEAD~12 && git commit
suggested by Chris Johnsen in his answer is that you get the commit message prepopulated with every commit message that you're squashing.
-
19You say this is more 'elegant' than
git rebase -i
, but you don't give a reason why. Tentatively -1ing this because it seems to me that in fact the opposite is true and this is a hack; aren't you performing more commands than necessary just in order to forcegit merge
into doing one of the things thatgit rebase
is specifically designed for? – Mark Amery Jul 8 '13 at 11:14 -
89@Mark Amery: There are various reasons that I said that this is more elegant. For example, it doesn't involve unnecessarily spawning an editor and then searching and replacing for a string in the "to-do" file. Using
git merge --squash
is also easier to use in a script. Essentially, the reasoning was that you don't need the "interactivity" ofgit rebase -i
at all for this. – Mark Longair Jul 8 '13 at 15:59 -
13Another advantage is that
git merge --squash
is less likely to produce merge conflicts in the face of moves/deletes/renames compared to rebasing, especially if you're merging from a local branch. (disclaimer: based on only one experience, correct me if this isn't true in the general case!) – Cheezmeister Feb 27 '14 at 22:21 -
2I'm always very reluctant when it comes to hard resets - I'd use a temporal tag instead of
HEAD@{1}
just to be on the safe side e.g. when your workflow is interrupted for an hour by a power outage etc. – Tobias Kienzler Aug 11 '14 at 12:18 -
9@B T: Destroyed your commit? :( I'm not sure what you mean by that. Anything that you committed you'll easily be able to get back to from git's reflog. If you had uncommitted work, but the files were staged, you should still be able to get their contents back, although that will be more work. If your work wasn't even staged, however, I'm afraid there's little that can be done; that's why the answer says up-front: "First check that git status is clean (since git reset --hard will throw away staged and unstaged changes)". – Mark Longair May 22 '16 at 9:55
I recommend avoiding git reset
when possible -- especially for Git-novices. Unless you really need to automate a process based on a number of commits, there is a less exotic way...
- Put the to-be-squashed commits on a working branch (if they aren't already) -- use gitk for this
- Check out the target branch (e.g. 'master')
git merge --squash (working branch name)
git commit
The commit message will be prepopulated based on the squash.
-
5This is the safest method : no reset soft / hard (!!), or reflog used ! – TeChn4K Nov 30 '16 at 14:08
-
21
-
2@Adam: Basically, this means use the GUI interface of
gitk
to label the line of code that you are squashing and also label the base upon which to squash to. In the normal case, both of these labels will already exist, so step (1) can be skipped. – Brent Bradburn Apr 11 '17 at 21:48 -
3Note that this method doesn't mark the working branch as being fully merged, so removing it requires forcing deletion. :( – Kyrstellaine Apr 13 '17 at 20:17
-
2For (1), I've found
git branch your-feature && git reset --hard HEAD~N
the most convenient way. However, it does involve git reset again, which this answer tried to avoid. – eis May 30 '17 at 17:01
Thanks to this handy blog post I found that you can use this command to squash the last 3 commits:
git rebase -i HEAD~3
This is handy as it works even when you are on a local branch with no tracking information/remote repo.
The command will open the interactive rebase editor which then allows you to reorder, squash, reword, etc as per normal.
Using the interactive rebase editor:
The interactive rebase editor shows the last three commits. This constraint was determined by HEAD~3
when running the command git rebase -i HEAD~3
.
The most recent commit, HEAD
, is displayed first on line 1. The lines starting with a #
are comments/documentation.
The documentation displayed is pretty clear. On any given line you can change the command from pick
to a command of your choice.
I prefer to use the command fixup
as this "squashes" the commit's changes into the commit on the line above and discards the commit's message.
As the commit on line 1 is HEAD
, in most cases you would leave this as pick
.
You cannot use squash
or fixup
as there is no other commit to squash the commit into.
You may also change the order of the commits. This allows you to squash or fixup commits that are not adjacent chronologically.
A practical everyday example
I've recently committed a new feature. Since then, I have committed two bug fixes. But now I have discovered a bug (or maybe just a spelling error) in the new feature I committed. How annoying! I don't want a new commit polluting my commit history!
The first thing I do is fix the mistake and make a new commit with the comment squash this into my new feature!
.
I then run git log
or gitk
and get the commit SHA of the new feature (in this case 1ff9460
).
Next, I bring up the interactive rebase editor with git rebase -i 1ff9460~
. The ~
after the commit SHA tells the editor to include that commit in the editor.
Next, I move the commit containing the fix (fe7f1e0
) to underneath the feature commit, and change pick
to fixup
.
When closing the editor, the fix will get squashed into the feature commit and my commit history will look nice and clean!
This works well when all the commits are local, but if you try to change any commits already pushed to the remote you can really cause problems for other devs that have checked out the same branch!
-
5do you have to pick the top one and squash the rest? You should edit your answer to explain how to use the interactive rebase editor in more detail – Kolob Canyon Sep 7 '18 at 17:35
-
2Yes, leave
pick
in line 1. If you choosesquash
orfixup
for the commit on line 1, git will show a message saying "error: cannot 'fixup' without a previous commit". Then it will give you the option to fix it: "You can fix this with 'git rebase --edit-todo' and then run 'git rebase --continue'." or you can just abort and start over: "Or you can abort the rebase with 'git rebase --abort'.". – br3nt Sep 10 '18 at 3:27 -
I am constantly using this command. I recommend to add an alias for that called
gr3
:alias gr3='git rebase -i HEAD~3'
– Flov Oct 13 '20 at 11:57 -
1@Timo, correct. Oldest at the top, newest at the bottom. That's why you need to
pick
the first line. And when you choosesquash
orfixup
on a line, it will put the changes into the commit on the line above. – br3nt Nov 8 '20 at 23:05 -
1This feels like the best answer when you know that you want to squash a certain amount of commits or at least see the commits you can squash by entering some arbitrary number. Generally, I use this . – Staghouse Jan 25 at 20:07
Based on Chris Johnsen's answer,
Add a global "squash" alias from bash: (or Git Bash on Windows)
git config --global alias.squash '!f(){ git reset --soft HEAD~${1} && git commit --edit -m"$(git log --format=%B --reverse HEAD..HEAD@{1})"; };f'
... or using Windows' Command Prompt:
git config --global alias.squash "!f(){ git reset --soft HEAD~${1} && git commit --edit -m\"$(git log --format=%B --reverse HEAD..HEAD@{1})\"; };f"
Your ~/.gitconfig
should now contain this alias:
[alias]
squash = "!f(){ git reset --soft HEAD~${1} && git commit --edit -m\"$(git log --format=%B --reverse HEAD..HEAD@{1})\"; };f"
Usage:
git squash N
... Which automatically squashes together the last N
commits, inclusive.
Note: The resultant commit message is a combination of all the squashed commits, in order. If you are unhappy with that, you can always git commit --amend
to modify it manually. (Or, edit the alias to match your tastes.)
-
6Interesting, but I'd much rather type the squashed commit message myself, as a descriptive summary of my multiple commits, than have it auto-entered for me. So I'd rather specify
git squash -m "New summary."
and haveN
determined automatically as the number of unpushed commits. – Acumenus Apr 22 '14 at 18:50 -
1@A-B-B, This sounds like a separate question. (I don't think it's exactly what the OP was asking; I've never felt a need for it in my git squash workflow.) – EthanB Apr 23 '14 at 22:29
-
3This is pretty sweet. Personally I'd like a version that uses the commit message from the first of the squashed-together commits. Would be good for things like whitespace tweaks. – funroll Jul 10 '14 at 1:40
-
@funroll Agreed. Just dropping the last commit msg is a super common need for me. We should be able to devise that... – Steve Clay Sep 26 '14 at 15:52
-
2@A-B-B you can use
git commit --amend
to further change the message, but this alias lets you have a good start on what should be in the commit message. – dashesy Jul 14 '16 at 15:59
2020 Simple solution without rebase :
git reset --soft HEAD~2
git commit -m "new commit message"
git push -f
2 means the last two commits will be squashed. You can replace it by any number
-
1This solution shouldn't be encouraged. Using the
-f (force)
option inpush
is a dangerous practice, particularly if you're pushing to a shared repo (i.e public history) that'll make life dfficult for contributors – FXQuantTrader Nov 17 '20 at 5:09 -
works good for the personal feature branches, should not be used on the branches where multiple people work, but I'd say latter may be in some cases just bad organization. – ivan.ukr Dec 31 '20 at 2:26
-
if the goal is to add this new commit to master as part of an ongoing pr, you could use
git reset --soft $(git merge-base feature master)
and thengit commit
. – Karl Pokus Feb 15 at 8:42
To do this you can use following git command.
git rebase -i HEAD~n
n(=4 here) is the number of last commit. Then you got following options,
pick 01d1124 Message....
pick 6340aaa Message....
pick ebfd367 Message....
pick 30e0ccb Message....
Update like below pick
one commit and squash
the others into the most recent,
p 01d1124 Message....
s 6340aaa Message....
s ebfd367 Message....
s 30e0ccb Message....
For details click on the Link
If you use TortoiseGit, you can the function Combine to one commit
:
- Open TortoiseGit context menu
- Select
Show Log
- Mark the relevant commits in the log view
- Select
Combine to one commit
from the context menu
This function automatically executes all necessary single git steps. Unfortunatly only available for Windows.
-
1As far as I am aware, this will not work for merge commits. – Thorkil Holm-Jacobsen Apr 26 '17 at 9:50
-
3Although it's not commented by any others, this even works for commits which are not at the HEAD. For instance, my need was to squash some WIP commits I did with a more sane description before pushing. Worked beautifully. Of course, I still hope I can learn how to do it by commands. – Charles Roberto Canato Apr 27 '18 at 22:03
-
Based on this article I found this method easier for my usecase.
My 'dev' branch was ahead of 'origin/dev' by 96 commits (so these commits were not pushed to the remote yet).
I wanted to squash these commits into one before pushing the change. I prefere to reset the branch to the state of 'origin/dev' (this will leave all changes from the 96 commits unstaged) and then commit the changes at once:
git reset origin/dev
git add --all
git commit -m 'my commit message'
-
1Just what I needed. Squash down commits from my feature branch, and then I git cherry pick that commit into my master. – David Victor Jul 10 '15 at 12:34
-
1
-
-
3@trudolf This isn't really squashing (picking individual commits to squash). This is more of committing all of your changes at once. – IgorGanapolsky Dec 3 '15 at 6:26
-
16
In the branch you would like to combine the commits on, run:
git rebase -i HEAD~(n number of commits back to review)
example:
git rebase -i HEAD~1
This will open the text editor and you must switch the 'pick' in front of each commit with 'squash' if you would like these commits to be merged together. From documentation:
p, pick = use commit
s, squash = use commit, but meld into previous commit
For example, if you are looking to merge all the commits into one, the 'pick' is the first commit you made and all future ones (placed below the first) should be set to 'squash'. If using vim, use :x in insert mode to save and exit the editor.
Then to continue the rebase:
git rebase --continue
For more on this and other ways to rewrite your commit history see this helpful post
-
2
-
The rebase will happen in blocks as it goes through the commits on your branch, after you
git add
the correct configuration in your files you usegit rebase --continue
to move to the next commit and start to merge.:x
is one command that will save the changes of the file when using vim see this – aabiro Nov 30 '18 at 16:51
Anomies answer is good, but I felt insecure about this so I decided to add a couple of screenshots.
Step 0: git log
See where you are with git log
. Most important, find the commit hash of the first commit you don't want to squash. So only the :
Step 1: git rebase
Execute git rebase -i [your hash]
, in my case:
$ git rebase -i 2d23ea524936e612fae1ac63c95b705db44d937d
Step 2: pick / squash what you want
In my case, I want to squash everything on the commit that was first in time. The ordering is from first to last, so exactly the other way as in git log
. In my case, I want:
Step 3: Adjust message(s)
If you have picked only one commit and squashed the rest, you can adjust one commit message:
That's it. Once you save this (:wq
), you're done. Have a look at it with git log
.
-
2
-
Procedure 1
1) Identify the commit short hash
# git log --pretty=oneline --abbrev-commit
abcd1234 Update to Fix for issue B
cdababcd Fix issue B
deab3412 Fix issue A
....
Here even git log --oneline
also can be used to get short hash.
2) If you want to squash (merge) last two commit
# git rebase -i deab3412
3) This opens up a nano
editor for merging. And it looks like below
....
pick cdababcd Fix issue B
pick abcd1234 Update to Fix for issue B
....
4) Rename the word pick
to squash
which is present before abcd1234
. After rename it should be like below.
....
pick cdababcd Fix issue B
squash abcd1234 Update to Fix for issue B
....
5) Now save and close the nano
editor. Press ctrl + o
and press Enter
to save. And then press ctrl + x
to exit the editor.
6) Then nano
editor again opens for updating comments, if necessary update it.
7) Now its squashed successfully, you can verify it by checking logs.
# git log --pretty=oneline --abbrev-commit
1122abcd Fix issue B
deab3412 Fix issue A
....
8) Now push to repo. Note to add +
sign before the branch name. This means forced push.
# git push origin +master
Note : This is based on using git on ubuntu
shell. If you are using different os (Windows
or Mac
) then above commands are same except editor. You might get different editor.
Procedure 2
- First add the required files for commit
git add <files>
- Then commit using
--fixup
option and theOLDCOMMIT
should be on which we need to merge(squash) this commit.
git commit --fixup=OLDCOMMIT
Now this creates a new commit on top of HEAD with fixup1 <OLDCOMMIT_MSG>
.
- Then execute below command to merge(squash) the new commit to the
OLDCOMMIT
.
git rebase --interactive --autosquash OLDCOMMIT^
Here ^
means the previous commit to OLDCOMMIT
. This rebase
command opens interactive window on a editor (vim or nano) on that
we no need to do anything just save and exiting is sufficient. Because the option passed to this will automatically move the latest
commit to next to old commit and change the operation to fixup
(equivalent to squash). Then rebase continues and finishes.
Procedure 3
- If need to add new changes to the last commit means
--amend
can be used withgit-commit
.
# git log --pretty=oneline --abbrev-commit
cdababcd Fix issue B
deab3412 Fix issue A
....
# git add <files> # New changes
# git commit --amend
# git log --pretty=oneline --abbrev-commit
1d4ab2e1 Fix issue B
deab3412 Fix issue A
....
Here --amend
merges the new changes to last commit cdababcd
and generates new commit ID 1d4ab2e1
Conclusion
- Advantage of 1st procedure is to squash multiple commits and to reorder. But this procedure will be difficult if we need to merge a fix to very old commit.
- So the 2nd procedure helps to merge the commit to very old commit easily.
- And the 3rd procedure is useful in a case to squash a new changes to last commit.
-
It only updates the last two commits even I reset to a commit Id to the 6th last commit, do not know why – Carlos Liu Jul 16 '18 at 7:06
-
If you are on a remote branch(called feature-branch
) cloned from a Golden Repository(golden_repo_name
), then here's the technique to squash your commits into one:
Checkout the golden repo
git checkout golden_repo_name
Create a new branch from it(golden repo) as follows
git checkout -b dev-branch
Squash merge with your local branch that you have already
git merge --squash feature-branch
Commit your changes (this will be the only commit that goes in dev-branch)
git commit -m "My feature complete"
Push the branch to your local repository
git push origin dev-branch
-
1Since I was just squashing ~100 commits (for syncing svn branches via git-svn), this is far faster than interactively rebasing! – sage Nov 3 '15 at 20:34
-
1Reading down, I see @Chris's comment, which is what I used to do (rebase --soft...) - too bad that stackoverflow is no longer putting the answer with hundreds of upvotes at the top... – sage Nov 3 '15 at 20:35
-
1agree with you @sage, lets hope they might do it sometime in the future – Sandesh Kumar Nov 3 '15 at 20:51
-
This is the right way. Rebase approach is good, but should only be used for squash as a last resort solution. – Axalix Mar 11 '19 at 20:13
-
If for example, you want to squash the last 3 commits to a single commit in a branch (remote repository) in for example: https://bitbucket.org
What I did is
git reset --soft HEAD~3
git commit
git push origin <branch_name> --force
-
5Just be careful, Since if you use force then there is no way to retrieve the previous commits since you removed it – Albert Ruelan Jul 3 '19 at 0:28
-
-
2Force is destructive. This is not squashing commits rather removing the last three commits and adding them back as a fourth (now new) commit, essentially rewriting the history which can break the repo for other users until they also force pull. This will also remove any other commits your team has pushed meanwhile. – Osama Shabrez Aug 31 '20 at 10:26
To squash the last 10 commits into 1 single commit:
git reset --soft HEAD~10 && git commit -m "squashed commit"
If you also want to update the remote branch with the squashed commit:
git push -f
-
--force is dangerous when multiple people are working on a shared branch as it blindly updates remote with your local copy. --force-with-lease could have been better as it makes sure that remote has no commits from others since you last fetched it. – bharath Feb 21 '20 at 19:30
I think the easiest way to do this is by making a new branch based on master and doing a merge --squash
of the feature branch.
git checkout master
git checkout -b feature_branch_squashed
git merge --squash feature_branch
Then you have all of the changes ready to commit.
-
This is a nice alternative to achieve a similar end result. I came looking on how to do it using rebase, but I chose this way better. I keep forgetting about the existence of
git merge
– Felipe Romero Oct 7 '20 at 2:11
What can be really convenient:
Find the commit hash you want to squash on top of, say d43e15
.
Now use
git reset d43e15
git commit -am 'new commit name'
-
2This. Why don't more people use this? It's way faster than rebasing and squashing individual commits. – a3y3 Jun 22 '19 at 19:51
This is super-duper kludgy, but in a kind of cool way, so I'll just toss it into the ring:
GIT_EDITOR='f() { if [ "$(basename $1)" = "git-rebase-todo" ]; then sed -i "2,\$s/pick/squash/" $1; else vim $1; fi }; f' git rebase -i foo~5 foo
Translation: provide a new "editor" for git which, if the filename to be edited is git-rebase-todo
(the interactive rebase prompt) changes all but the first "pick" to "squash", and otherwise spawns vim - so that when you're prompted to edit the squashed commit message, you get vim. (And obviously I was squashing the last five commits on branch foo, but you could change that however you like.)
I'd probably do what Mark Longair suggested, though.
-
7+1: that's fun and instructive, in that it's wasn't at all obvious to me that you can put anything more complex than the name of a program in the GIT_EDITOR environment variable. – Mark Longair Mar 4 '11 at 21:04
-
You could simplify this using
gawk
.git -c core.editor="gawk -i inplace '{if(NR>1 && \$1==\"pick\"){\$1=\"squash\"} print \$0}'" rebase -i --autosquash HEAD~5
. – typesanitizer Aug 30 '20 at 8:56
If you want to squish every commit into a single commit (e.g. when releasing a project publicly for the first time), try:
git checkout --orphan <new-branch>
git commit
Simple one-liner that always works, given that you are currently on the branch you want to squash, master is the branch it originated from, and the latest commit contains the commit message and author you wish to use:
git reset --soft $(git merge-base HEAD master) && git commit --reuse-message=HEAD@{1}
-
4I have been absolutely livid with frustration about squashing commits and how stupidly complicated it is - just effing use the last message and squash them all to one commit! Why is it that hard???? This one liner does that for me. Thank you from the bottom of my angry heart. – Locane May 7 '19 at 20:41
⚠️ WARNING: "My last X commits" might be ambiguous.
(MASTER)
Fleetwood Mac Fritz
║ ║
Add Danny Lindsey Stevie
Kirwan Buckingham Nicks
║ ╚═══╦══════╝
Add Christine ║
Perfect Buckingham
║ Nicks
LA1974══════════╝
║
║
Bill <══════ YOU ARE EDITING HERE
Clinton (CHECKED OUT, CURRENT WORKING DIRECTORY)
In this very abbreviated history of the https://github.com/fleetwood-mac/band-history repository you have opened a pull request to merge in the the Bill Clinton commit into the original (MASTER
) Fleetwood Mac commit.
You opened a pull request and on GitHub you see this:
Four commits:
- Add Danny Kirwan
- Add Christine Perfect
- LA1974
- Bill Clinton
Thinking that nobody would ever care to read the full repository history. (There actually is a repository, click the link above!) You decide to squash these commits. So you go and run git reset --soft HEAD~4 && git commit
. Then you git push --force
it onto GitHub to clean up your PR.
And what happens? You just made single commit that get from Fritz to Bill Clinton. Because you forgot that yesterday you were working on the Buckingham Nicks version of this project. And git log
doesn't match what you see on GitHub.
🐻 MORAL OF THE STORY
- Find the exact files you want to get to, and
git checkout
them - Find the exact prior commit you want to keep in history, and
git reset --soft
that - Make a
git commit
that warps directly from the from to the to
-
1This is 100% the easiest way to do this. If your current HEAD is the correct state you want, then you can skip #1. – Stan Feb 6 '19 at 22:26
-
This is the only way I know that allows to rewrite the first commit history. – Vadorequest Nov 19 '19 at 12:18
If you don't care about the commit messages of the in-between commits, you can use
git reset --mixed <commit-hash-into-which-you-want-to-squash>
git commit -a --amend
If you're working with GitLab, you can just click the Squash option in the Merge Request as shown below. The commit message will be the title of the Merge Request.
-
With
GitLab Enterprise Edition 12.8.6-ee
it just randomly took a commit message for the squashed commit... – Wolfson Jun 9 '20 at 12:23
I find a more generic solution is not to specify 'N' commits, but rather the branch/commit-id you want to squash on top of. This is less error-prone than counting the commits up to a specific commit—just specify the tag directly, or if you really want to count you can specify HEAD~N.
In my workflow, I start a branch, and my first commit on that branch summarizes the goal (i.e. it's usually what I will push as the 'final' message for the feature to the public repository.) So when I'm done, all I want to do is git squash master
back to the first message and then I'm ready to push.
I use the alias:
squash = !EDITOR="\"_() { sed -n 's/^pick //p' \"\\$1\"; sed -i .tmp '2,\\$s/^pick/f/' \"\\$1\"; }; _\"" git rebase -i
This will dump the history being squashed before it does so—this gives you a chance to recover by grabbing an old commit ID off the console if you want to revert. (Solaris users note it uses the GNU sed -i
option, Mac and Linux users should be fine with this.)
-
I tried the alias but I'm not sure if the sed replaces are having any effect. What should they do? – raine Mar 21 '15 at 18:04
-
The first sed just dumps the history to the console. The second sed replaces all the 'pick' with 'f' (fixup) and rewrites the editor file in-place (the -i option). So the second one does all the work. – Ethan Apr 22 '15 at 20:28
-
You are right, counting N-number of specific commits is very error prone. It has screwed me up several times and wasted hours trying to undo the rebase. – IgorGanapolsky Oct 2 '15 at 0:37
-
Hi Ethan, I would like to know if this workflow will hide possible conflicts on the merge. So please consider if you have two branches master and slave. If the slave has a conflict with the master and we use
git squash master
when we are checked out on the slave. what will it happen? will we hide the conflict? – Sergio Bilello Feb 24 '16 at 7:55 -
@Sergio This is a case of rewriting history, so you probably will have conflicts if you squash commits that have already been pushed, and then try to merge/rebase the squashed version back. (Some trivial cases might get away with it.) – Ethan Jun 28 '16 at 1:51
git rebase -i HEAD^^
where the number of ^'s is X
(in this case, squash the two last commits)
In addition to other excellent answers, I'd like to add how git rebase -i
always confuses me with the commit order - older to newer one or vice versa? So this is my workflow:
git rebase -i HEAD~[N]
, where N is the number of commits I want to join, starting from the most recent one. Sogit rebase -i HEAD~5
would mean "squash the last 5 commits into a new one";- the editor pops up, showing the list of commits I want to merge. Now they are displayed in reverse order: the older commit is on top. Mark as "squash" or "s" all the commits in there except the first/older one: it will be used as a starting point. Save and close the editor;
- the editor pops up again with a default message for the new commit: change it to your needs, save and close. Squash completed!
What about an answer for the question related to a workflow like this?
- many local commits, mixed with multiple merges FROM master,
- finally a push to remote,
- PR and merge TO master by reviewer.
(Yes, it would be easier for the developer to
merge --squash
after the PR, but the team thought that would slow down the process.)
I haven't seen a workflow like that on this page. (That may be my eyes.) If I understand rebase
correctly, multiple merges would require multiple conflict resolutions. I do NOT want even to think about that!
So, this seems to work for us.
git pull master
git checkout -b new-branch
git checkout -b new-branch-temp
- edit and commit a lot locally, merge master regularly
git checkout new-branch
git merge --squash new-branch-temp
// puts all changes in stagegit commit 'one message to rule them all'
git push
- Reviewer does PR and merges to master.
-
From many opinions I like your approach. It's very convenient and fast – Artem Solovev Sep 5 '18 at 9:57
In question it could be ambiguous what is meant by "last".
for example git log --graph
outputs the following (simplified):
* commit H0
|
* merge
|\
| * commit B0
| |
| * commit B1
| |
* | commit H1
| |
* | commit H2
|/
|
Then last commits by time are H0, merge, B0. To squash them you will have to rebase your merged branch on commit H1.
The problem is that H0 contains H1 and H2 (and generally more commits before merge and after branching) while B0 don't. So you have to manage changes from H0, merge, H1, H2, B0 at least.
It's possible to use rebase but in different manner then in others mentioned answers:
rebase -i HEAD~2
This will show you choice options (as mentioned in other answers):
pick B1
pick B0
pick H0
Put squash instead of pick to H0:
pick B1
pick B0
s H0
After save and exit rebase will apply commits in turn after H1. That means that it will ask you to resolve conflicts again (where HEAD will be H1 at first and then accumulating commits as they are applied).
After rebase will finish you can choose message for squashed H0 and B0:
* commit squashed H0 and B0
|
* commit B1
|
* commit H1
|
* commit H2
|
P.S. If you just do some reset to BO:
(for example, using reset --mixed
that is explained in more detail here https://stackoverflow.com/a/18690845/2405850):
git reset --mixed hash_of_commit_B0
git add .
git commit -m 'some commit message'
then you squash into B0 changes of H0, H1, H2 (losing completely commits for changes after branching and before merge.
How can I squash my last X commits together into one commit using Git?
git rebase -i HEAD~X
The following content will be shown:
pick 1bffc15c My earlier commit
pick 474bf0c2 My recent commit
# ...
For the commits that you want to squash, replace pick with fixup, so it becomes:
pick 1bffc15c My earlier commit
fixup 474bf0c2 My recent commit
# ...
If it's open in vim (default interface within terminal), then press Esc
on your keyboard, type :wq
and Enter
to save the file.
Verify: Check git log