Rebasing is useful if you want to change a commit message, squash commits together or merge with other commits. A good rule of thumb is not to rebase when others are working on the same project as you as it can cause merge conflicts. I use this primarily to squash my smaller commits into larger commits.
Step 1
Run the following command:
git rebase -i HEAD~X
X
is the number of commits you want to change.
-i
means interactive. You can also use -interactive
instead of -i
.
Step 2
After running you will see the interactive git page in your terminal looking something like this:
pick fda59df Delete CNAME
pick x536897 Better README
pick c01a668 Change the commit message but push the same commit.
# Rebase 49687a0..d426a8a onto 49687a0
# # Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#
Step 3
Editing your commits:
Your terminal should look like this after if you want to only reword
commits.
pick fda59df Delete CNAME
reword x536897 Better README
reword c01a668 Change the commit message but push the same commit.
You don't need to replace each commit as unchanged commits will be ignored.
To save your edits press :wq
(save and quit), your editor will open once more to ask for a new commit message for the edited commit if you selected anything other than pick
.
Note: Putting a #
infront of the commit message if you are squashing removes it from git. This only works for squashing as you cannot commit an empty commit.
Step 4
Push the changes to your repo. By using the following
git push --force
Use --force
or --f
if you've already pushed the commits.
You only need to force a push once until you need to rebase after pushing multiple commits remotely.
If you get an error message like this:
fatal: It seems that there is already a rebase-merge directory, and
I wonder if you are in the middle of another rebase. If that is the
case, please try
git rebase (--continue | --abort | --skip)
If that is not the case, please
rm -fr ".git/rebase-merge"
and run me again. I am stopping in case you still have something
valuable there.
You can cancel rebase any time by running:
git rebase --abort