Rewriting History with Rebase and Cherry-Pick

Git keeps every commit as a snapshot with a parent link. git rebase replays your commits on top of a new base, which produces a straight, readable history. git cherry-pick copies one specific commit onto the current branch.

A common workflow is to update a feature branch with the latest main branch before opening a pull request:

bash git fetch origin git switch feature/search git rebase origin/main

If a conflict appears, fix the files, mark them as resolved, and continue:

bash git add src/search.js git rebase --continue

To abandon the rebase and return to where you started, run git rebase --abort.

Cherry-pick is useful for backporting a fix:

bash git log --oneline origin/main | head -5 git cherry-pick 3f9a1c2

Rules that prevent trouble:

- Never rebase commits that other people have already pulled into shared branches. - Use git push --force-with-lease instead of --force, because it refuses to overwrite commits you have not fetched. - Use git reflog to find commits after a mistaken rebase, since Git keeps them for a while even when no branch points to them.

If you only want to change the last commit message or add a missed file, git commit --amend is the simpler tool.