How do I squash my last N commits together?

3.7m views Asked by At

How do I squash my last N commits together into one commit?

46

There are 46 answers

21
Anomie On BEST ANSWER

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.

4
Ariel Gabizon On

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'
16
Mark Longair On

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.

0
Happy Lee On

I was inspired by Chris Johnsen's answer and find a better solution.

If we wanna squash the last 3 commits, and write the new commit message from scratch, this suffices:

git reset --soft HEAD~3 && git commit

If we wanna squash the last many commits, lets say 162 commits, it's very hard to count the rank of the 162th commit, but we can use the commit ID, this suffices:

git reset --soft ceb5ab28ca && git commit

ceb5ab28ca is the commit ID of the 162th commit.

2
slisnychyi On

simple solution:

git reset --soft HEAD~5

git commit -m "commit message"

git push origin branch --force-with-lease

0
SSteve On

If you're using GitUp, select the commit you want to merge with its parent and press S. You have to do it once for each commit, but it's much more straightforward than coming up with the correct command line incantation. Especially if it's something you only do once in a while.

0
User12547645 On

Let's say n is really large. You do not want to deal with each commit. You just want a new branch called new_feature_branch that has 1 commit and all your changes of old_feature_branch. You can do the following

git checkout main 

# will contain changes all changes from old_feature_branch 
git checkout -b new_feature_branch 

# get all changes from old_feature_branch and stage them
for f in $(git --no-pager diff --name-only old_feature_branch ) ; do git checkout old_feature_branch -- $f ; done

git commit -m "one commit message"
8
trudolf On

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'
4
Pranav Wadhwa On

Easiest way to do this is using GitHub Desktop. Just select all the commits in your History, right-click and select "Squash x commits":

GitHub Desktop squash

0
Ahmad Awais On

Just add this bash function to your bash of .zshrc file.

# Squash last X commits with a Commit message.
# Usage: squash X 'COMMIT_MSG'
# where X= Number of last commits.
# where COMMIT_MSG= New commit msg.
function squash() {
    if [ -z "${1}" -o -z "${2}" ]; then
        echo "Usage: \`squash X COMMIT_MSG\`"
        echo "X= Number of last commits."
        echo "COMMIT_MSG= New commit msg."
        return 1
    fi

    git reset --soft HEAD~"$1"
    git add . && git ci -m "$2" # With 100 emoji
    git push --force
}

Then just run

squash X 'New Commit Message'

And you're done.

0
littlewhywhat On

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.

2
rashok On

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

  1. First add the required files for commit
git add <files>
  1. Then commit using --fixup option and the OLDCOMMIT 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>.

  1. 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

  1. If need to add new changes to the last commit means --amend can be used with git-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.
3
Pulkit Bansal On

Many answers are based on git rebase command, but in my experience it is somewhat complex and advanced for git-beginners.

Let's say you want to squash last 3 commits. Then following are the steps:

  • Note down current commit id: Use git log -1 --oneline and note the commit-id of the present state (just in case you do something wrong with git reset)
  • Go back 3 commits: Using git reset --soft HEAD~3 you'll go back 3 commits (and sort of forget that you've had made these three commits earlier)
  • Do a new commit: Now simply do git commit -m <NEW_SINGLE_MESSAGE> which will automatically combine the three commits under your message

In case something goes wrong with git reset, you can again return to the original state by git reset --soft <ORIGINAL_COMMIT>

1
Eyal On

If you are on windows, you might want to use this powershell code.

function SquashCommits([int]$count) {
$commitHashes = git log --pretty=format:%h -n $count    

$commands= ( 0..$($count-2) ) |  %{   "sed -i 's/^pick $($commitHashes[$_])/squash $($commitHashes[$_])/' `$file"    }
$st= $commands -join "`n"

$st="func() { 
local file=`$1
$st 
}; func"
$env:GIT_SEQUENCE_EDITOR=$st
try{
        git rebase -i HEAD~$count
    }finally
    {
        Remove-Item Env:\GIT_SEQUENCE_EDITOR
    }
}

Usage Example:

SquashCommits 3
0
Sam On

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

38
Chris Johnsen On

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”).

Edit Based on Comments

You have rewritten that history you must than use the --force flag to push this branch back to remote. This is what the force flag is meant for, but you can be extra careful, and always fully define your target.

git push --force-with-lease origin <branch-name>
3
Cascabel On

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.

1
rnwed_user On

method 1 if you have many commits

git rebase -i master then press keyboard 'i' to edit

you will see like this:

pick etc1
pick etc2
pick etc2

replace the word pick with 'f' and press esc y :wq

pick etc1 //this commit will the one commit
f etc2
f etc2

and press this command

git push origin +head

method 2 if you have few commits you can do this to delete a commit, you need to do same for delete your second commit and so on

git reset --soft HEAD^1 // or git reset --soft head~1
git commit --amend //then press `:wq` 
git push -f

method 3 if you already have one commit and you dont want submit another commit more

git add files...
git commit --amend  //then press `:wq`
git push origin +head
0
ana On

Here is another visual example of what would follow after executing: git rebase -i HEAD~3

Here there is a visual example of what would follow after executing git rebase for the three last commits

Source: https://www.git-tower.com/learn/git/faq/git-squash/

0
William Denniss On

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
1
allenjom On

What about an answer for the question related to a workflow like this?

  1. many local commits, mixed with multiple merges FROM master,
  2. finally a push to remote,
  3. 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.

  1. git pull master
  2. git checkout -b new-branch
  3. git checkout -b new-branch-temp
  4. edit and commit a lot locally, merge master regularly
  5. git checkout new-branch
  6. git merge --squash new-branch-temp // puts all changes in stage
  7. git commit 'one message to rule them all'
  8. git push
  9. Reviewer does PR and merges to master.
2
Martin Thoma On

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 :

enter image description here

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:

enter image description here

Step 3: Adjust message(s)

If you have picked only one commit and squashed the rest, you can adjust one commit message:

enter image description here

That's it. Once you save this (:wq), you're done. Have a look at it with git log.

1
Ayan On

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
0
Alan Dong On

First I find out the number of commits between my feature branch and current master branch by

git checkout master
git rev-list master.. --count

Then, I create another branch based out my-feature branch, keep my-feature branch untouched.

Lastly, I run

git checkout my-feature
git checkout -b my-rebased-feature
git checkout master
git checkout my-rebased-feature
git rebase master
git rebase head^x -i
// fixup/pick/rewrite
git push origin my-rebased-feature -f // force, if my-rebased-feature was ever pushed, otherwise no need for -f flag
// make a PR with clean history, delete both my-feature and my-rebased-feature after merge

Hope it helps, thanks.

5
Sandesh Kumar On

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:

  1. Checkout the golden repo

    git checkout golden_repo_name
    
  2. Create a new branch from it(golden repo) as follows

    git checkout -b dev-branch
    
  3. Squash merge with your local branch that you have already

    git merge --squash feature-branch
    
  4. Commit your changes (this will be the only commit that goes in dev-branch)

    git commit -m "My feature complete"
    
  5. Push the branch to your local repository

    git push origin dev-branch
    
0
Zsolt Z. On

If you don't care about the commit messages of the in-between commits, you can use

git reset --soft <commit-hash-into-which-you-want-to-squash>
git commit -a --amend
1
arush436 On

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.

enter image description here

12
EthanB On

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.)

2
aabiro On

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~2

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 add .

git rebase --continue

For more on this and other ways to rewrite your commit history see this helpful post

2
Saurav Sahu On

Did anyone mention how easy it is to do on IntelliJ IDEA UI:

  • Go to git window
  • Manually select all the commits you want to merge into one.
  • Right-click > Squash Commits > Edit the squashed commit message
  • Click on branch name on left side > Right-click > Push > Force Push

enter image description here

17
Xys On

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

0
ironmongrrrl On

We were really happy with this answer, it means you don't need to count through commits.

If you have loads of commits on master branch and want to combine them all into one:

  • Ensure you're on the master branch and do git status to ensure it's all clean
  • Copy the commit SHA for the commit BEFORE you started your work
  • git reset ‒soft commitIdSHA

[ You'll notice that all your changes at this point will be shown in the source control section of your IDE - good to review them to check it's all there]

  • git commit -am "the message you want that will replace all the other commit messages"
  • git push (will complain as you are behind on the commits) so do git push --force

That's it!

7
Ethan On

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.)

1
ColinM On

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}
2
William Entriken On

⚠️ 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

  1. Find the exact files you want to get to, and git checkout them
  2. Find the exact prior commit you want to keep in history, and git reset --soft that
  3. Make a git commit that warps directly from the from to the to
0
Ignorant On

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:

  1. git rebase -i HEAD~[N] , where N is the number of commits I want to join, starting from the most recent one. So git rebase -i HEAD~5 would mean "squash the last 5 commits into a new one";
  2. 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;
  3. the editor pops up again with a default message for the new commit: change it to your needs, save and close. Squash completed!

Sources & additional reads: #1, #2.

6
user1376350 On

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.

0
ccpizza On

Variation of existing answers for the specific case when the remote is configured to disallow --force; assuming the commits are in a branch that you have permissions to delete remotely:

# 'rewind' to last commit before your commit (use `git log` to identify)
git reset <hash-BEFORE-first-commit-in-feature>

# re-add files (new and modified)
git add <modified-and-new-files> 

# make new single commit with all changes
git commit -m <new-single-commit-message> 

# delete remote branch if you already pushed a PR
git push origin --delete <feature-branch-name>

git push -u origin <feature-branch-name>
1
Yoaz Menda On
git rebase -i HEAD^^

where the number of ^'s is X

(in this case, squash the two last commits)

4
Matthias M On

If you use TortoiseGit, you can the function Combine to one commit:

  1. Open TortoiseGit context menu
  2. Select Show Log
  3. Mark the relevant commits in the log view
  4. Select Combine to one commit from the context menu

Combine commits

This function automatically executes all necessary single git steps. Unfortunatly only available for Windows.

12
br3nt On

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:

See the Git docs on using the interactive rebase. A summary follows:

From the example above, 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 commits are listed in reverse order to what you may expect. The oldest commit is displayed on line 1, and the newest commit on the last line. 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.

interactive rebase editor


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!

enter image description here

3
dvvrt On

To avoid having to resolve any merge conflicts when rebasing onto a commit in the same branch, you can use the following command

git rebase -i <last commit id before your changes start> -s recursive -X ours

To squash all commits into one, when you are prompted to edit commits to be merged (-i flag), update all but first action from pick to squash as recommended in other answers too.

Here, we use the merge strategy (-s flag) recursive and strategy option (-X) ours to make sure that the later commits in the history win any merge conflicts.

NOTE: Do not confuse this with git rebase -s ours which does something else.

Reference: git rebase recursive merge strategy

14
Brent Bradburn On

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...

  1. Put the to-be-squashed commits on a working branch (if they aren't already) -- use gitk for this
  2. Check out the target branch (e.g. 'master')
  3. git merge --squash (working branch name)
  4. git commit

The commit message will be prepopulated based on the squash.

0
Himanshu Shekhar On

Tried all approaches mention here. But finally my issue resolved by following this link. https://gist.github.com/longtimeago/f7055aa4c3bba8a62197

$ git fetch upstream
$ git checkout omgpull 
$ git rebase -i upstream/master

 < choose squash for all of your commits, except the first one >
 < Edit the commit message to make sense, and describe all your changes >

$ git push origin omgpull -f
1
Jakir Hosen Khan On

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

3
Albert Ruelan On

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

  1. git reset --soft HEAD~3
  2. git commit
  3. git push origin <branch_name> --force