Remove File from Latest Commit

Better Stack Team
Updated on June 24, 2024

To remove a file from the latest commit in Git, you can use the git reset command in combination with the --soft option and HEAD^ reference to reset the commit to the previous state while keeping the changes staged in the working directory. Then, you can unstage the file and commit the changes again. Here's how:

 
# Reset the latest commit while keeping the changes staged
git reset --soft HEAD^

# Unstage the file you want to remove
git reset HEAD <file-to-remove>

# Commit the changes again
git commit -m "Updated commit message"

Replace <file-to-remove> with the path to the file you want to remove from the latest commit.

Note:

  • Be cautious when rewriting commit history, especially if the commit has already been pushed to a remote repository. If the commit has been shared with others, it's generally not recommended to rewrite its history.
  • After performing these commands, you'll have a modified commit history, and you'll need to force-push (git push --force) the changes to update the remote repository if necessary.
Got an article suggestion? Let us know
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github