How to change past commit to include a missed file?

Solution 1:

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!

Solution 2:

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