Inorder to squash multiple commits into one in Git, you can use the interactive rebase feature. Follow these steps:

Open your terminal or command prompt and navigate to the repository.

  • Run the following command to start the interactive rebase:
           git rebase -i HEAD~N
  • Replace N with the number of commits you want to squash. For example, if you want to squash the last 3 commits, use HEAD~3.
  • A text editor will open with a list of commits in reverse order. The oldest commit will be at the top and the newest commit at the bottom.
  • Identify the commits you want to squash and replace the word “pick” with “squash” or “s” in front of each commit you want to combine. Leave the first commit with “pick” as is.
  • Save and close the editor.
  • Git will now combine the selected commits into one commit and open a new text editor for you to enter a new commit message. Edit the message as desired, save, and close the editor.
  • Finally, force-push your changes to the remote repository with the following command:
        git push -f

Note: You should only use the git push -f command if you are working on a personal branch or if you have the consent of all other contributors to overwrite the remote branch’s history.

GIT Rebase: Merge commits into Single Commit:

As shown in below we will merge the first two commits into bc30c80,da0a945 into 4985258(Latest commit)

Press I and change pick to as shown in below

Now push the changes with git push and you will get error saying updates are rejected

$ git push
To github-jayaram509.com:jayaram509/gitdemo.git
 ! [rejected]        main -> main (non-fast-forward)
error: failed to push some refs to 'github-jayaram509.com:jayaram509/gitdemo.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Use git push -f to push the changes:

$ git push -f

Enumerating objects: 8, done.
Counting objects: 100% (8/8), done.
Delta compression using up to 8 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (7/7), 543 bytes | 543.00 KiB/s, done.
Total 7 (delta 0), reused 0 (delta 0), pack-reused 0
To github-jayaram509.com:jayaram509/gitdemo.git
 + 4985258...6cc280f main -> main (forced update)

GIT Rebase demo completed