How to add file to a previous commit?
To add a new file to the previous commit:
$ git add new-file
$ git commit --amend
You can use git commit --amend --no-edit
if you don't want to change the commit message.
Here's an amusing flowchart1 which is also surprisingly handy: it gives the correct recommendation both for the original question and for the amended "What if it weren't the last commit?" question.
1 Taken from http://justinhileman.info/article/git-pretty/
Add a file to a previous commit
If you have already pushed the branch you are working on, please see the man pages first. In particular, please note:
Rebasing (or any other form of rewriting) a branch that others have based work on is a bad idea: anyone downstream of it is forced to manually fix their history.
However, if you haven't pushed your branch, prepare to enter the danger zone.
Find the commit hash
First, you need to know the commit hash of the commit that you want to add to. This is shown by git log
. You actually want to specify the commit prior to the one you want to add to. (You can think of it as the start index to the slice of commits you want to alter.) You can make sure you have the right commit by running git log -1 HEAD~n
. Where 'n' is an integer you increment until you have the right commit. Or you could count, no really.
But, if you do count, at least confirm you have the right commit with git log -1 HEAD~5
or whatever your count was. You should NOT see the commit you want to add to.
DANGER, heh
Now you are ready to run git rebase -i HEAD~5
, or use a commit hash instead git rebase -i hash^
. This will bring up your favorite text editor and a file to edit. The file is the todo list for the rebase command. The comments in the file tell you what options you have. Simply find the line with the commit you want to add to, and on that line change 'pick' to 'edit'. Now save and close the file.
The rebase will stop once it reaches the commit you told it to edit. Run a git status
to see the extra information it provides. Stage your files to add to the commit with git add .
or whatever the filenames are.
Then, do git commit --amend
or git commit --amend --no-edit
(if you don't want to edit the commit message). This will amend the commit you chose to edit.
Finally, run git rebase --continue
.
If in doubt, on Linux you can find out more by reading through the docs output by man git-rebase
or git --help rebase
.