Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a file to the last commit in Git? [duplicate]

Tags:

git

Sometimes after I did a commit, I found out that I left out a file which should also be included in the commit, but was actually not. I often committed again:

git add the_left_out_file git commit "include the file which should be added in the last commit" 

I think it might not be a good idea to do so. I want to just include the file without adding a commit. Something like this,

git add the_left_out_file git add_staged_files_to_previous_commit 

Is it possible?

like image 340
Searene Avatar asked Nov 09 '16 09:11

Searene


People also ask

How do you add a file to the last commit?

Changing the Last Commit: git commit --amend. The git commit --amend command is a convenient way to modify the most recent commit. It lets you combine staged changes with the previous commit instead of creating an entirely new commit.

How do I amend a last second commit?

To change the most recent commit message, use the git commit --amend command. To change older or multiple commit messages, use git rebase -i HEAD~N .

Can I amend old commit?

You can use git rebase --interactive , using the edit command on the commit you want to amend.


Video Answer


2 Answers

Yes, there's a command, git commit --amend, which is used to "fix" the last commit.

In your case, it would be called as:

git add the_left_out_file git commit --amend --no-edit 

The --no-edit flag allows to make an amendment to the commit without changing the commit message.

Warning

You should never amend public commits that you already pushed to a public repository, because amend is actually removing the last commit from the history and creating a new commit with the combined changes from that commit and new added when amending.

like image 153
Konrad 'Zegis' Avatar answered Sep 17 '22 19:09

Konrad 'Zegis'


If you didn't push the update in remote then the simple solution is remove the last local commit using the following command:

git reset HEAD^ 

Then add all files and commit again.

like image 29
Muhammed Imran Hussain Avatar answered Sep 20 '22 19:09

Muhammed Imran Hussain