appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Rebase, stash and cherry-pick

Lesson 3 of 412 minIntermediate

Rewrite your own history to keep it linear, and move work around safely.

Rebase replays your commits on top of another base. It gives a straight, linear history, with no merge commits for every update.

git switch feature
git fetch origin
git rebase origin/main     # replay my commits on the latest main

If a commit conflicts, fix the files, git add them and run git rebase --continue (or git rebase --abort to cancel).

CarefulRebase rewrites commit ids. Only rebase commits that nobody else has based work on. Never rebase a shared branch such as main.

Tidy your commits before a PR

git rebase -i HEAD~4        # edit the last four commits

The editor lists them. Change pick to squash to merge a commit into the previous one, reword to change the message, or drop to remove it.

Stash

git stash push -m "wip login"   # shelve uncommitted changes
git switch other-branch
git stash pop                   # bring them back

Cherry-pick

git cherry-pick 3f2a9c1         # copy one commit onto the current branch

NoteMerge keeps history exactly as it happened. Rebase makes it readable. Many teams rebase their own branch and then merge it with a merge commit or a squash.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. When is it unsafe to rebase?
2. What does squash do in an interactive rebase?
Hintgit stash

Key terms