乐闻世界logo
搜索文章和话题

How to Remove Files from Git Without Deleting Them from the File System?

2024年7月4日 09:37

When you need to remove a file from Git version control while keeping it intact on your local file system, you can use the git rm --cached command. This command removes the file from Git's tracking list but does not delete the physical file.

Suppose you have a file named example.txt that has been tracked by Git, and you decide not to have Git track it anymore, but you still need it on your local file system.

You can follow these steps:

  1. Open your terminal: Launch your command-line interface.
  2. Navigate to the repository directory: Use the cd command to move to the directory containing your Git repository.
    bash
    cd path/to/your/git/repository
  3. Execute the removal command: Use the git rm --cached command with the filename to untrack the file.
    bash
    git rm --cached example.txt
    This command removes example.txt from Git's tracking list but leaves it preserved on your local disk.
  4. Verify the changes: Run the git status command to check the current state; you should see example.txt marked as 'deleted'.
    bash
    git status
  5. Commit the changes: Finally, commit this update to your Git history.
    bash
    git commit -m "Remove example.txt from Git tracking"

By following these steps, you have successfully removed example.txt from Git version control without deleting it from the file system. This method is particularly useful when you accidentally track files that should not be under version control, such as log files or configuration files.

标签:Git