How to rewrite commit messages in Git

Arif Billah Babu

         

  git



Image not found!!

Rewriting commit messages in Git can be done using the git commit --amend command. Here are the steps to rewrite commit messages:

Changing the Last Commit Message:

  1. Make your changes:

    bash
    git commit --amend -m "New and improved commit message"

    This will open your default text editor with the previous commit message. Make your desired changes, save, and close the editor.

  2. Save changes: If you are using a command-line text editor, save and close the file.

  3. Push changes: If you have already pushed the previous commit to a remote repository, you will need to force-push the changes.

    bash
    git push --force

    Be cautious when force-pushing, especially if you are collaborating with others.

Changing Older Commit Messages:

  1. Identify the commit to edit: Use git log to find the SHA-1 hash of the commit you want to edit.

  2. Interactively rebase:

    bash
    git rebase -i <commit_hash>^

    Replace <commit_hash> with the SHA-1 hash of the commit before the one you want to edit.

  3. Change the command from 'pick' to 'reword': In the interactive rebase editor, change the word 'pick' to 'reword' next to the commit you want to edit.

  4. Save and close the editor: If you're using a command-line text editor, save and close the file.

  5. Edit the commit message: This will open another editor where you can modify the commit message. Make your changes, save, and close the editor.

  6. Complete the rebase: After editing the commit message, Git will continue with the rebase process. If there are no conflicts, it will finish successfully.

  7. Push changes: If you have already pushed the commit to a remote repository, you will need to force-push the changes.

    bash
    git push --force

    Be cautious with force-push, especially in a collaborative environment.

Remember to use caution when rewriting commit history, especially if you've already shared the commit with others. It's generally not recommended to rewrite history on branches that others might be working on.