Git

How to Remove File from Git Using git rm Command

Developers mainly use Git for tracking a project’s source code. On this version control system, they can perform different options on local repositories, such as creating repositories, files, folders, branches, tags, and many more. Moreover, Git also permits you to remove the file, folders, branches, and tags by utilizing the “$ git rm -f” command.

This post provides the method to remove the file from Git.

How to Remove/Delete a File from Git Using git rm Command?

To remove a file from Git, firstly, navigate to the repository, and initialize it. Next, create and track a file to the staging area. Commit changes to update the repository. Create one more file and track it to the staging area. Then, display the content list and run the “$ git rm -f <file>” command.

Let’s move ahead and implement the above-discussed scenario one by one!

Step 1: Move to Repository

First, move to the desired directory from which you need to remove a file or folder:

$ cd "C:\Users\nazma\Git\Alpha"

Step 2: Initialize Git Repository

Initialize the Git repository using the “git init” command:

$ git init

Step 3: Update File

Next, execute the below-given command to either create a new file or update the specified file:

$ echo Linuxhint > file1.txt

Step 4: Track File

Track a file to the staging area using the “git add” command with the file name:

$ git add file1.txt

Step 5: Update Repository

Run the “git commit” command to update the repository by committing the changes:

$ git commit -m "Added new file"

Step 6: Update File

Again, update the file if required:

$ echo hello > file2.txt

Step 7: Track File

Track a file to the staging area by executing the provided command:

$ git add file2.txt

Step 8: Update Repository

Run the provided command to update the repository:

$ git commit -m "file2.txt added"

Step 9: View List

Execute the “ls” command to view the list of content:

$ ls

It can be observed that currently, our repository has the following two files:

Step 10: Remove File

Execute the “git rm” command with the “-f” flag and specify the file name to remove it forcefully:

$ git rm -f file1.txt

Step 11: View Content

View the list of files to verify the performed operation:

$ ls

It can be observed that “file1.txt” has been successfully removed from the repository:

That’s all! We have compiled the easiest procedure to remove/delete the file from Git.

Conclusion

To remove the file from Git, first, navigate to the Git repository and initialize it. Then, create and add a file to the repository. Commit changes to update the repository. Next, view the list of content and execute the “$ git rm -f <file>” command. This post provided the method to delete the file from Git.

About the author

Maria Naz

I hold a master's degree in computer science. I am passionate about my work, exploring new technologies, learning programming languages, and I love to share my knowledge with the world.