git rebase
Move a branch's commits onto a new base, or rewrite the last commits
What it does
git rebase main takes the commits of the current branch and replays them on top of the latest main, as if the work had just started. History stays straight, with no merge commits. If a commit conflicts with the new base, git stops: fix the files, stage them with git add and go on with git rebase --continue, or cancel it all with git rebase --abort.
With -i rebase becomes interactive: git opens an editor with a list of commits, where you can keep each one (pick), reword it (reword), fold it into the previous one (squash) or drop it (drop). That is how history gets tidied up before a pull request.
Careful. rebase creates new commits in place of the old ones. Do not rebase commits that are already on a shared branch: your teammates' history will split from yours. After a rebase, push your own branch with git push --force-with-lease.
Syntax
git rebase <branch>
git rebase -i <commit>
git rebase --continue
git rebase --abortExamples
Move the current branch’s commits on top of the latest main
git rebase mainrebase— rewrite the branch on top of anothermain— the new base
Interactively edit the last three commits
git rebase -i HEAD~3same as:
git rebase --interactive HEAD~3rebase— rewrite history-i— interactively: squash, reword, dropHEAD~3— the last three commits