Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change past commit to include a missed file?

Tags:

git

git-commit

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?

like image 243
kolrie Avatar asked Jan 16 '13 22:01

kolrie


People also ask

How do I change a file from a previous commit?

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.


2 Answers

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!

like image 78
DrBeco Avatar answered Sep 23 '22 09:09

DrBeco


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

like image 23
Rafał Rawicki Avatar answered Sep 22 '22 09:09

Rafał Rawicki