git rebase
- Version
- 2.51
- Review
- Draft
Summary#
git rebase replays commits on a new base, usually giving the replayed commits new IDs. With upstream and an optional branch, it replays what the branch has and the upstream lacks. --onto chooses the new base separately from the point where selection starts.
Syntax#
git rebase main topic
git rebase --onto new-base old-base topic
git rebase -i base
git rebase --continue
git rebase --abort
Example#
(
set -eu
scratch=$(mktemp -d "${TMPDIR:-/tmp}/devlookup-git.XXXXXX")
trap 'rm -rf -- "$scratch"' EXIT
unset GIT_CONFIG_GLOBAL $(git rev-parse --local-env-vars)
export GIT_CONFIG_NOSYSTEM=1 GIT_TEMPLATE_DIR= LC_ALL=C
export HOME="$scratch" XDG_CONFIG_HOME="$scratch" GIT_ATTR_NOSYSTEM=1
export GIT_PAGER=cat GIT_EDITOR=true
mkdir "$scratch/work"
cd "$scratch/work"
git init -q -b trunk
git config user.name "Reference Example"
git config user.email example@example.invalid
commit_file() {
printf '%s\n' "$2" > "$1"
git add "$1"
git commit -qm "$2"
}
commit_file base.txt "Start"
git switch -q -c parser
commit_file parser.txt "Add parser"
git switch -q -c cli
commit_file cli.txt "Add CLI"
git switch -q trunk
commit_file docs.txt "Fix docs"
# Replay only the commits in parser..cli on top of trunk.
git rebase -q --onto trunk parser cli
git branch --show-current
git log --format=%s
# Replay the commits that parser has and trunk lacks.
git rebase -q trunk parser
git branch --show-current
git log --format=%s
)
Expected output#
cli
Add CLI
Fix docs
Start
parser
Add parser
Fix docs
Start
Common mistakes#
During a rebase conflict, ours is the new base plus the commits replayed so far, and theirs is your commit being applied, the reverse of what many people expect. Avoid rebasing commits that others have built on.
Version applicability#
Git 1.5.3 added interactive rebase. Git 2.38 added --update-refs, which also moves branches pointing to rewritten commits. The option skips other branches checked out in a worktree.
The complete example requires Git 2.28 or later for git init -b.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0