701

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Searene
  • 25,920
  • 39
  • 129
  • 186
  • also, another explanation of the same: http://stackoverflow.com/questions/26050327/how-does-git-commit-amend-work-exactly – quetzalcoatl Nov 09 '16 at 09:32
  • Found this awesome article: https://medium.com/@igor_marques/git-basics-adding-more-changes-to-your-last-commit-1629344cb9a8 – infiniteLearner Feb 18 '22 at 06:22

2 Answers2

1390

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Konrad 'Zegis'
  • 15,101
  • 1
  • 16
  • 18
  • 5
    I saw the EDIT in @konrad-zeguis answer *after* doing the commit... How can 'git commit --amend --no-edit' be undone? – emagar Feb 03 '18 at 14:10
  • Try 'git reset HEAD@{1}' which will put you back one commit. You can use 'git reflog' to get a full list of commits, and use it to reset to 'HEAD@{n}' where n is the commit to which you would like to roll back. – TheHiggsBroson May 23 '19 at 18:29
  • 51
    Just to remind, at the end you should use: **git push --force**, because this way you are rewriting the commits tree – Boncho Valkov Jul 09 '19 at 15:19
  • 1
    with `git status` you can get the filename and copy it instead of typing it. – Andre Elrico Jul 23 '19 at 15:59
  • 6
    If you want to push to remote repository execute this command : **git push -f origin some_branch** [link](https://medium.com/@igor_marques/git-basics-adding-more-changes-to-your-last-commit-1629344cb9a8) – Nouar Sep 14 '19 at 23:18
  • 4
    Note that amending the commit (with or without message edit) does not change the *commit date* nor the *author*. To make it transparent when and who did what, I recommend `git commit --amend --no-edit --date=now --reset-author` – mgaert Dec 08 '21 at 11:00
59

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131