0
0
Gitdevops~5 mins

Golden rule of rebasing (never rebase public) in Git - Commands & Configuration

Choose your learning style9 modes available
Introduction
Rebasing changes the history of your commits. If you rebase commits that others have already used, it can cause confusion and conflicts. The golden rule is to never rebase commits that are public and shared with others.
When you want to clean up your local commit history before sharing your work.
When you want to update your feature branch with the latest changes from the main branch before merging.
When you want to avoid creating unnecessary merge commits in your private branch.
When you want to reorder or squash your local commits to make them clearer before pushing.
When you want to keep your local work tidy without affecting others.
Commands
Switch to your feature branch where you want to rebase commits.
Terminal
git checkout feature-branch
Expected OutputExpected
Switched to branch 'feature-branch'
Rebase your feature branch on top of the latest main branch commits to update your work.
Terminal
git rebase main
Expected OutputExpected
First, rewinding head to replay your work on top of it... Applying: Your commit message here
Force push your rebased branch to update the remote branch safely, only if no one else has pushed changes.
Terminal
git push --force-with-lease
Expected OutputExpected
To github.com:user/repo.git + abc1234...def5678 feature-branch -> feature-branch (forced update)
--force-with-lease - Force push only if remote branch has not changed to avoid overwriting others' work
Check your commit history to confirm the rebase worked and commits are in the right order.
Terminal
git log --oneline
Expected OutputExpected
def5678 Your commit message here abc1234 Previous commit message
Key Concept

If you remember nothing else from this pattern, remember: never rebase commits that have been shared with others to avoid breaking their work.

Common Mistakes
Rebasing a branch that others have already pulled and based their work on.
It rewrites commit history, causing conflicts and confusion for others who have the old history.
Only rebase local or private branches that no one else uses. For shared branches, use merge instead.
Using 'git push --force' without checking if others pushed changes.
It can overwrite others' commits and cause data loss.
Use 'git push --force-with-lease' to safely force push only if no one else updated the branch.
Summary
Rebase only local or private branches to clean up commit history.
Never rebase branches that others have pulled or shared publicly.
Use 'git push --force-with-lease' to safely update rebased branches.
Check commit history after rebasing to confirm changes.