简体   繁体   中英

Files listed in .gitignore are removed with git rm command

I have setup a .gitignore file with just one file in it:

 cat .gitignore
 README.md

The .gitignore file has these permissions:

ls -l README.md
-rw-r--r-- 1 tdun0002 1049089 113 Mar 21 18:54 README.md

I'm not sure what the problem is but when I do a git rm --force * everything is removed including the README.md file listed in the .gitignore file.

What am I doing wrong?

The .gitignore file is a way of specifying which untracked files will remain untracked even if you try to add them (and it's generally a good idea that any changes to it should be fully committed before attempting operations that use those changes). It is not a way to tell general git commands to not do stuff with a file.

In particular, if a file is already in the repo when you add it to the .gitignore , this will have no effect on it.

Since your README.md was already in the repo when you added it to .gitignore , it continued to be a tracked file.


Though that might not solve your actual issue: I'm having a hard time figuring out what your intent is, since this appears to be an XY problem - you're asking why the thing you tried didn't work, when we don't actually know what you were trying to do. The two possibilities that come to mind are discussed below:

  1. If your intent is to not have README.md in the repo, just git rm it, then commit/push/etc.

  2. If you do want it in the repo, it shouldn't be listed in the .gitignore file.

  3. If you want to get rid of everything except a few files (and they're clean, in the sense that there are no uncommitted changes), you might find it easier to delete the lot then just check out the ones you want to keep. Something like git rm . ; git checkout HEAD -- README.md git rm . ; git checkout HEAD -- README.md git rm . ; git checkout HEAD -- README.md .

  4. If you only want to remove specific files, you can use wildcards to limit them. For example, git rm --dry-run [0-9a-zA-QS-Z]* will not touch any files starting with R . You'll notice I've used --dry-run here since you'll probably want to check this option before allowing it to actually delete. Once you're happy it will do the right thing, just run it again without that option.

If it's something else you're trying to achieve, it'd be handy if you could expand on that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM