1 min read

Rebasing With Git

Rebasing With Git

Rebasing is one of the features you probably want to have, if you plan to work on a neat git-based project.


🍣 Where to Rebase?

If you know how many commits you make, to rebase you use git rebase with -i flag to enable interactive rebasing. The HEAD~ corresponds to the number of commits you have done (e.g., HEAD~4 if you have 4 commits to rollback to get to common ancestor commit).

git rebase -i HEAD~

Sometimes, you commit a lot and forget how many commits you’d make. To know the least common anscestor you have with master, you do git merge-base with your branch name as parameter.

git merge-base  master

The above command will return a git hash which you can use on the git rebase command.

If you already know the git hash, then you can roll back to that specific commit and move all current changes to unstaged. Once, the editor pop-ups you will choose which commit to retain, squash, and reword.

git rebase -i 

🍣 Merge Latest from Master

If you’ve already rebased your changes and needed to get the latest changes from master. All you have to do is rebase to the latest changes from master.
This command will do that.

git rebase origin/master

In any case, you’ve encountered some conflict, first resolve it then continue rebasing instead of creating a new merge commit.

git rebase --continue

🍣 Overwriting Remote Repo Changes

Once all is done, overwrite your remote repo latest changes if you’ve pushed it. This will do a force push ignoring current ref on remote repo.

git push -f

🍣 Did Something Wrong? In Need of Rollback

Did something go wrong with merging conflicts? Don’t worry you can still see your previous changes using the command git reflog short for reference log.
You can check out the reference hash then re-merge your changes.

git reflog

References