Horje
How to Remove a File from Git without Deleting it Locally?

Git is a widely used distributed version control and source code management system. It effectively tracks changes to source code, enabling effortless branching, merging, and versioning. There may be instances where we need to remove a file from the Git repository, but want to keep it in your local filesystem. This situation can arise for a configuration file.

Steps to Remove a File from a Git Repository without Deleting it From the Local Filesystem

Step 1: Check the current status of your repository

Suppose we’re working on a Git repository. Now we want to see all the files in the filesystem and the current status of the Git repository.

For Linux or MacOS:

ls && git status

For Windows:

dir && git status
Screenshot_2024-05-23-09-59-12_1920x1080

Output

I have two C source files named “index.c” and “main.c”. Both of these files have been committed and are currently being tracked by Git.

Step 2: Remove the File from the Git Repository

To remove a file from the Git repository without deleting it from your local filesystem, we’ll need to use the git rm command with the –cached option.

Now let’s try to remove index.c from the git repository

git rm --cached file-name.extension

Output:

Screenshot_2024-05-23-10-07-44_1920x1080

Output

We can see, the index.c file is “deleted“. Further, since its local copy is still there, it has been marked as “untracked”.

Step 3: Commit Changes

Now commit the changes

git commit -m "commit message"

Output:

Screenshot_2024-05-23-10-30-00_1920x1080

Output

We can see index.c is deleted from the git repository.

Step 4: Final Output

Now check the currently staged files.

git ls-files

and all files in the local filesystem respectively.

ls

Output:

Screenshot_2024-05-23-10-32-06_1920x1080

Output

The output shows the index.c file is not there anymore. But local copies are kept. We have removed the file from the git repository successfully and the file is now untracked but remember that the files removed by git rm -–cached still live in Git’s commit history.




Reffered: https://www.geeksforgeeks.org


Git

Related
Git Shallow Clone: Optimizing Repository Size Git Shallow Clone: Optimizing Repository Size
How to Fix GitHub Error: Authentication Failed from the Command Line ? How to Fix GitHub Error: Authentication Failed from the Command Line ?
How to List and Show the Git Stash History? How to List and Show the Git Stash History?
How to Determine the URL that a local Git repository was Originally Cloned From? How to Determine the URL that a local Git repository was Originally Cloned From?
How to Reset or Revert a File to a Specific Revision in Git? How to Reset or Revert a File to a Specific Revision in Git?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
16