Git Rebase Interactive Mode Best Practices

Git Rebase Interactive Mode Best Practices

Learn how to edit typos in a commit and combine commits.

Β·

3 min read

Hey there πŸ‘‹πŸ»! You might have come across a situation during the development of a feature where your git commits get lengthy or you commit with a typo. This is where you can use git rebase in interactive mode to modify commits.

git rebase allows us to combine commits on top of another branch's commits. By using its interactive mode -i or --interactive, we can also modify commits.

-i , --interactive - let the user edit the list of commits to rebase

Git Rebase Interactive mode

We can use squash, reword and other options provided by its interactive mode. Here, this example contains unnecessary commits and also a typo. We will use squash and reword.

$ git log
commit 82e7eebc2ab107b9ce5eaeb50c1725d981725d74 (HEAD -> master)
Author: Rohini Chandra 
Date:   Sun Jun 19 12:12:50 2022 +0530
    code refactr
commit c8c7641a0b763379981b7df1c9d5232f3d373679
Author: Rohini Chandra
Date:   Sun Jun 19 12:11:41 2022 +0530
    minor fix
commit c299b936fbec0704c20853461fe0e6ba0742a1fe
Author: Rohini Chandra 
Date:   Sun Jun 19 12:10:37 2022 +0530
    added test-file

Use git rebase -i HEAD~{X} command to get into the interactive mode. HEAD~{X} - takes the last X commits from HEAD. It opens in an editor.

pick c8c7641 minor fix
pick 82e7eeb code refactr

# Rebase c299b93..82e7eeb onto c299b93 (2 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
....

Reword

Press Insert key to edit. Replacing pick with r or reword against a commit you want to edit commit message.

....
pick c8c7641 minor fix
reword 82e7eeb code refactr
....

Then exit from the insert mode using Esc and type :x or :wq to save the changes. It will again take you to the editor to modify the commit message. Modify and then save the changes.

code refactor

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
....

Squash

If you don't want to have unnecessary commits before pushing the commits, use squash. This is useful for cleaning up history before pushing changes to a remote branch. Squash a commit by replacing pick with s or squash against a commit.

pick c8c7641 minor fix
squash 82e7eeb code refactor

# Rebase c299b93..82e7eeb onto c299b93 (2 commands)
....

pick will take all the below squash commits.

$ git log
commit dec7641a0b763379981b7df1c9d5232f3d373679 (HEAD -> master)
Author: Rohini Chandra
Date:   Sun Jun 19 12:11:41 2022 +0530
    minor fix
commit c299b936fbec0704c20853461fe0e6ba0742a1fe
Author: Rohini Chandra 
Date:   Sun Jun 19 12:10:37 2022 +0530
    added test-file

Thanks for reading! If you find this useful please do like and share πŸ˜‡

Β