How to change past commit to include a missed file?

If you have NOT pushed these 4 commits, you can do it as follows:

Create patch files for all these commits:

git format-patch -4

Rewind back by 4 commits:

git reset --hard HEAD~4

Add missing file:

git add missing-file

Commit it with --amend:

git commit --amend

Apply all saved patches back:

git am *.patch

If you have pushed, you should NOT use this method. Instead, just admit your blunder and create one more commit on top of HEAD which fixes this issue.


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

Tags:

Git

Git Commit