git rebase

Estimated reading: 2 minutes 13 views

The git rebase command is used to integrate changes from one branch into another while maintaining a linear commit history. Instead of merging, which creates a merge commit, git rebase reapplies commits from the source branch onto the target branch as if they were made sequentially.

Optional Commands with git rebase

You can enhance the functionality of git rebase with these options:

OptionDescriptionExample
git rebase <branch>Reapplies commits from the current branch onto the specified branch.git rebase main reapplies current branch commits on top of main.
git rebase -i <base>Starts an interactive rebase to edit, squash, or reorder commits.git rebase -i HEAD~3 starts an interactive rebase for the last 3 commits.
git rebase --abortAborts the rebase process and restores the branch to its original state.git rebase --abort cancels the rebase.
git rebase --continueContinues the rebase after resolving conflicts.git rebase --continue resumes the process.
git rebase --onto <newbase>Moves a series of commits onto a different branch or commit.git rebase --onto main featureA featureB moves changes from featureA onto main.

Syntax and Example

				
					# Rebase the current branch onto the main branch
git rebase main
# Example output:
# Successfully rebased and updated refs/heads/feature/login.

# Start an interactive rebase for the last 3 commits
git rebase -i HEAD~3
# Example output:
# pick abc123 Added login module
# pick def456 Fixed login bug
# pick ghi789 Updated login tests
# (Interactive editor opens to allow commit editing.)

# Abort the rebase process
git rebase --abort
# Example output:
# (No output if successful; the branch is restored to its original state.)

# Continue rebase after resolving conflicts
git rebase --continue
# Example output:
# [detached HEAD abc1234] Merged conflicts for rebase.

				
			

Why Use git rebase?

  • Clean History: Keeps a linear commit history, making it easier to follow changes.
  • Avoid Merge Commits: Rebase removes the clutter of merge commits in the project history.
  • Interactive Control: Options like -i let you edit, reorder, or squash commits during the rebase process.

Conclusion

The git rebase command is a powerful tool for streamlining Git history and ensuring a clear, linear structure. While it offers enhanced clarity, caution is necessary when using it in shared branches to avoid rewriting public history.

Leave a Comment

Share this Doc

git rebase

Or copy link

CONTENTS