How to un-commit and remove files accidentally committed to git

Last modified date

Comments: 0

Problem

Let’s say you accidentally commit some files to your git repository that shouldn’t be committed.

You need to remove the files but adding to the gitignore is not working since you have already committed the files.

How do you remove the files from your git repo without deleting them as this will not work?

Solution

Step 1 – Tell git to ignore the files

Add the file names to your .gitignore file.

Step 2 – Remove the files from git’s index

Run the command:

git rm -r --cached <<NAME OF FILES TO REMOVE FROM GIT>>

This will tell git to remove the files from being tracked rm and perform the operation recursively -r.

--cached is git’s index so we are removing references to the files changes from git’s cache.

Then commit these changes and you will see that in the git status, your .gitignore will be updated and the committed files are being removed from the repo.

Then you are done!

JakTech

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.