I have committed a change and forgot to add a file to the change set. After other commits, I realized the file is now missing from a HEAD^4
commit.
How do I rewrite a previous commit to include the missing file?
You can modify the most recent commit in the same branch by running git commit --amend. This command is convenient for adding new or updated files to the previous commit. It is also a simple way to edit or add comments to the previous commit. Use git commit --amend to modify the most recent commit.
I realize people can google and come here to find a simpler answer: What if it was just the last commit? (OP's question is for fixing the 4th commit back in history)
In the case you commit and realize you forgot to add some file immediately, just do:
# edited file-that-i-remember.txt git add file-that-i-remember.txt git commit # realize you forgot a file git add file-that-i-forgot.txt git commit --amend --no-edit
Where --no-edit
will keep the same commit message.
Easy peasy!
Use git rebase --interactive HEAD~4
and set edit
option for the commit you'd like to amend.
Remember that you should not modify commits pushed to the remote repository this way. It's better to add a new commit with missing file in that case.
To make this more clear, first stash any current changes with git stash
. Then, git rebase --interactive HEAD~4
. You get the following in a text editor (note that you'll get 5 commits, in descending order):
pick 123e123 fifth last commit message pick 321e122 fourth last commit message pick 1d23e3f third last commit message pick 987a987 second last commit message pick 8a8a8a8 last commit message
Modify the change entry's prefix from pick
to edit
. That'd be edit 321e122 ...
for the OP.
git rebase
goes through the entries, in order. As there's only one we're changing, you'll only have one entry to change. Now, add your files with git add
, and git commit --amend
to amend the current commit with those added files.
Finally, git rebase --continue
moves onto the next file. As there's only one, the rebase is complete
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With