Git

How to Keep Your Git History Clean With Interactive Rebase?

Git local repository involves a large number of commits that creates clutter and takes more space in Git memory. Clearing Git history is important to avoid any issues. In such circumstances, merge all the commits or a particular range of commits into a single commit.

This tutorial will briefly demonstrate the method for keeping the Git history clean with interactive rebase.

How to Keep Your Git History Clean With Interactive Rebase?

To keep the Git history clean with the interactive rebase, follow the below-given instructions:

  • Move to the Git local repository.
  • Check the Git log.
  • Clean Git history by merging multiple commits into a single commit.
  • Verify changes by viewing the Git log.

Step 1: Navigate to Local Repository

First, head straight to the Git local repository by executing the “cd” command:

cd "C:\Users\user\Git\testrepo"

Step 2: Check Git Log

Run the “git log –oneline” command to list commit history with less detail:

git log --oneline

The below-stated output shows that all the commits have been listed successfully:

Step 3: Cleaning Git History

To clean the Git history, merge a specific range of commits into a single commit by using the “git rebase” command with the “-i” flag for interactive mode. To set the range of the commits, used the “HEAD” with desired range:

git rebase -i HEAD~4

As a result, a file will open up with the default text editor including the specified range of commits:

Now, change the stated “pick” keyword with the “squash” with all the commits that need to merge. Then, close the editor after saving the changes by pressing the “CTRL + S” keys:

Step 4: Add Commit

Next, add the new commit message in the text editor, save changes, and close it:

According to the provided output, all the changes committed, and Git history has been cleaned successfully:

Step 5: Verify Changes

Lastly, verify all the added changes by executing the below-given command:

git log --oneline

It can be noticed that all the changes have been merged in a single commit:

That’s all about cleaning the Git history with the help of interactive rebase.

Conclusion

To keep the Git history clean with interactive rebase, the user can merge all or a specific range of commits into a single commit. For that instance, the “git rebase -i HEAD” command can be used. Where “HEAD~4” is used to select the commits to the range “4” and the “-i” flag is utilized for interactive mode. Then, replace the “pick” keyword with the “squash” and save the changes. This post has stated the method for keeping the Git history clean using interactive rebase.

About the author

Hafsa Javed