DEV Community

Possawat Sanorkam
Possawat Sanorkam

Posted on • Updated on

Git Rebase: The Power Tool for Clean Git Histories

Here is an example of using git rebase to incorporate the latest changes from the master branch into a feature branch:

$ git checkout feature
# switch to the feature branch

$ git rebase master
# apply the commits from the feature branch on top of the latest commits in the master branch

# If there are conflicts during the rebase, you will need to resolve them
# and then use `git add` to mark the resolved files, and then use
# `git rebase --continue` to continue the rebase.

$ git push -f origin feature
# push the feature branch to the remote repository, using the -f flag to force the push
# (necessary because the commit history of the feature branch has been modified by the rebase)
Enter fullscreen mode Exit fullscreen mode

Here is an example of using git rebase to "squash" multiple commits into a single commit:

$ git checkout feature
# switch to the feature branch

$ git rebase -i HEAD~3
# interactively rebase the last 3 commits

# This will open a text editor, showing the list of commits that will be modified by the rebase.
# You can use the `squash` command to merge commits together. For example:
#
# pick abcdefg Some commit message
# squash hijklmn Another commit message
# squash opqrstu Yet another commit message

# Save and close the editor. Git will then apply the changes and open another editor
# for you to modify the commit message of the combined commit.

$ git push -f origin feature
# push the feature branch to the remote repository, using the -f flag to force the push
# (necessary because the commit history of the feature branch has been modified by the rebase)
Enter fullscreen mode Exit fullscreen mode

It's important to note that git rebase should be used with caution, as it modifies the existing commit history of a branch. This can make the commit history more difficult to understand and can cause problems if other people are working on the same branch.

Therefore, it's usually a good idea to use git merge instead of git rebase when working with other people.

Surprise, this article was generated by ChatGPT!

Top comments (0)