How to Remove Files From a Repository in Git

Azhar Bashir Khan Feb 02, 2024
How to Remove Files From a Repository in Git

This tutorial will show how to remove files from a Git repository.

Git enables a collaborative development environment. Thus, many files are committed into a Git repository by a team of developers.

Often, we encounter some files that are no longer necessary or are redundant. In such cases, we would deem it fit to delete such files or folders already committed into the repository.

We will now illustrate this with an example.

Using git rm to Remove Files and Folders in Git Repository

Suppose we have a folder named folder1 in the Git repository. Also, consider that this folder has two files, file1 and file2.

$ ls folder1/
file1  file2

To delete a file in the Git repository, we need to do as follows.

$ git rm <filename>

$ git commit -m "commit message"

$ git push origin branch_name

The first command deletes a file from the Git repository and the filesystem. The subsequent commands are used to commit the changes and push the change (i.e.) file deletion into the remote repository.

Thus, to delete file1, we will do as follows in our example.

$ cd folder1

$  git rm file1
rm 'folder1/file1'

We have moved into folder1 and deleted file1 from the repository and the filesystem.

We can check the status of the deletion as follows.

$ git status
On branch main
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

	deleted:    file1

Now, we will commit this deletion as follows.

$ git commit -m "deleted file"
[main 27ec53b] deleted file
 1 file changed, 0 insertions(+), 0 deletions(-)
 delete mode 100644 folder1/file1
 
$ git push origin main

Sometimes, we may wish to delete the file only from the repository and not from the filesystem. We may want to use that file for some other purpose.

To only delete files from the repository and not from the filesystem, we need to do the following.

$ git rm --cached file2

$ git commit -m "Removed file2 from repository only"

$ git push origin main

When we run the git rm command with the --cached option, the files are removed from the repository but not from the working tree (i.e.) the filesystem.

Sometimes, we may need to delete the entire folder.

To do this, we need to add the option -r to the git rm command as follows.

$ git rm -r folder1
rm 'folder1/file2'

$ git commit -m "removed folder1"
[main dabfe02] removed folder1
 1 file changed, 0 insertions(+), 0 deletions(-)
 delete mode 100644 folder1/file2
 
$ git push origin main

Thus, in our example, we have now deleted folder viz. folder1 along with its contents.

For more information on git rm, explore the following site - git rm.

Related Article - Git Repository