711

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?

2

2 Answers 2

1413

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.

6
  • 5
    I saw the EDIT in @konrad-zeguis answer after doing the commit... How can 'git commit --amend --no-edit' be undone?
    – emagar
    Feb 3, 2018 at 14:10
  • 53
    Just to remind, at the end you should use: git push --force, because this way you are rewriting the commits tree Jul 9, 2019 at 15:19
  • 1
    with git status you can get the filename and copy it instead of typing it. Jul 23, 2019 at 15:59
  • 6
    If you want to push to remote repository execute this command : git push -f origin some_branch link
    – Nouar
    Sep 14, 2019 at 23:18
  • 5
    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 8, 2021 at 11:00
60

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.

6
  • 3
    Cool trick, Muhammed! Can you add a brief explaination about HEAD^ to your answer?
    – kevinarpe
    Mar 19, 2018 at 7:43
  • 17
    HEAD^ is a reference to the commit before the latest commit on the current branch. HEAD is a reference to the latest commit on the current branch.
    – Jason
    Mar 20, 2018 at 13:36
  • 14
    ^ represents -1, and HEAD represents the current position pointer in git. Thus, HEAD^ represents 1 commit before the latest commit. Apr 10, 2018 at 17:04
  • 2
    git commit --amend -m "your new message" Nov 4, 2019 at 7:12
  • 3
    Not a good answer because this command doesn't add a file to the last commit. It removes the last commit entirely to be redone, which is not the same thing. May 18, 2022 at 22:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.