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
1commit 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 usevim
or …), press theins
button to edit the content, if you want to keep any commits, then edit thepick
of the remaining commits tof
- 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 onlycommit one
left
- Step 1: Use the command:
- Extending: Now I want to edit the content of
commit one
tocommit 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
tocommit abc
and then save - Step 4: Use
git log --oneline
to check, now you see onlycommit one
left
- Ok, here I have completed the first part about basic damage about git, wish you success!