Squashing multiple commits into one with GIT

Tram Ho

How to merge multiple commits into one git?

First we have to understand the structure of git locally – on our computers, like

  • The local Git generally has 3 parts:
    • working: the code we see and work on.
    • staging area: when we implement git add ... the code will be in this part.
    • local repo: when making git commit ... then the code will be in this part.

Go to the main point

  • For example, my local has 3 commits
    • 104c487 (HEAD -> master) commit three
    • ba64718 commit two
    • 6e43b7c commit one
  • Now I want to merge these 3 commits into 1 (for example, the content of the 1st commit one 1 commit one )
    • Step 1: Use the command: git rebase -i HEAD~3 (HEAD ~ 3 is because the number of commits you want to merge is 3 from HEAD, if n is HEAD ~ n)
    • Step 2: After I use vi to edit (you can use vim or …), press the ins button to edit the content, if you want to keep any commits, then edit the pick of the remaining commits to f
      • pick 6e43b7c commit one
      • f ba64718 commit two
      • f 104c487 commit three
    • Step 3: Press Esc -> :qw -> Enter to save the changes.
    • Step 4: Use git log --oneline to check, now you see only commit one left
  • Extending: Now I want to edit the content of commit one to commit abc ?
    • Step 1: do the same as above.
    • Step 2: Do the same as above, but the pre-committed pick is kept as follows:
      • r 6e43b7c commit one changed
      • f ba64718 commit two
      • f 104c487 commit three
    • Step 3: Do the same as above, but then it goes to another screen for us to rewrite the commit content, we edit commit one to commit abc and then save
    • Step 4: Use git log --oneline to check, now you see only commit one left
  • Ok, here I have completed the first part about basic damage about git, wish you success!
Share the news now

Source : Viblo