Remove file from latest commit

15    Asked by MaxVance in Devops , Asked on May 15, 2025

How can you remove a file from the latest Git commit without deleting it from your working directory? Learn the steps to undo or adjust your last commit to clean up mistakes or exclude files before pushing.

Answered by John Simpson

If you've accidentally added a file to your latest Git commit and want to remove it (without deleting it from your working directory), don’t worry — it’s totally fixable! You can amend your last commit to exclude the file using just a few commands.

Here’s how you can do it:

 Steps to Remove a File from the Latest Commit

Reset the file (unstage it):

  git reset HEAD 

  1.  This removes the file from the staging area but keeps it in your working directory.

Amend the previous commit:

  git commit --amend

  1.  This opens your commit message in an editor. You can keep the same message or update it. Save and close the editor.

(Optional) If you've already pushed the commit:

 You'll need to force push:

  git push origin branch-name --force

  Be careful with force pushes, especially on shared branches — it can affect others’ work.

 A few things to keep in mind:

  • The file stays in your project folder, just not in the commit anymore.
  • If you don’t want to include the file in future commits, consider adding it to .gitignore.
  • Always double-check before amending a pushed commit — it's safe for solo work, risky on teams.

This is a common scenario and a great example of how flexible Git is. You’re not stuck with your mistakes — you can tidy things up easily before pushing code!



Your Answer

Interviews

Parent Categories