Search code examples
gitgit-rebase

Git - Modify an old commit with the file currently in my working directory


So I've committed a file that was wrong, it is not my last commit (it is HEAD~9). And I wanted to replace that file with the version I currently have in my working directory.

I was going to do a rebase interactive but I realised I need to clean first my working directory which has the file with I want to replace the old version in HEAD~9.

There are similar questions but didn't find an answer that addresses this scenario. Which is the way to proceed in this case?


Solution

  • It sounds like an interactive rebase would give you what you want. You would first need to commit the file in a "temporary" commit. Then through the interactive rebase you can fixup HEAD~9.

    1. git add <file>
    2. git commit -m 'fixup commit'
    3. git rebase -i HEAD~10
    4. In the editor move fixup commit directly after HEAD~9 and set it to f for fixup.
    5. Save and close the editor

    A fixup is a squash but retains the commit message of the commit being squashed into. If any of the commits between HEAD and HEAD~9 also modify that file, then you may get merge conflicts when the commits are replayed.