How can I delete a file from git repo?

2019-01-01 11:17发布

I have added a file named "file1.txt" to git repo. After that I committed it, added a couple directories called dir1 and dir2, and committed them to git repo.

Now the current repo has "file1.txt", dir1 and dir2.
How can I delete "file1.txt" without affecting others like dir1 and dir2?

标签: git git-rm
18条回答
余生请多指教
2楼-- · 2019-01-01 12:14

I have obj and bin files that accidentally made it into the repo that I don't want polluting my 'changed files' list

After I noticed they went to the remote, I ignored them by adding this to .gitignore

/*/obj
/*/bin

Problem is they are already in the remote, and when they get changed, they pop up as changed and pollute the changed file list.

To stop seeing them, you need to delete the whole folder from the remote repository.

In a command prompt:

  1. CD to the repo folder (i.e. C:\repos\MyRepo)
  2. I want to delete SSIS\obj. It seems you can only delete at the top level, so you now need to CD into SSIS: (i.e. C:\repos\MyRepo\SSIS)
  3. Now type the magic incantation git rm -r -f obj
    • rm=remove
    • -r = recursively remove
    • -f = means force, cause you really mean it
    • obj is the folder
  4. Now run git commit -m "remove obj folder"

I got an alarming message saying 13 files changed 315222 deletions

Then because I didn't want to have to look up the CMD line, I went into Visual Sstudio and did a Sync to apply it to the remote

查看更多
无色无味的生活
3楼-- · 2019-01-01 12:18

Use git rm:

git rm file1.txt
git commit -m "remove file1.txt"

But if you want to remove the file only from the Git repository and not remove it from the filesystem, use:

git rm --cached file1.txt
git commit -m "remove file1.txt"

And to push changes to remote repo

git push origin branch_name  
查看更多
姐姐魅力值爆表
4楼-- · 2019-01-01 12:20

After you have removed the file from the repo with git rm you can use BFG Repo-Cleaner to completely and easily obliterate the file from the repo history.

查看更多
不流泪的眼
5楼-- · 2019-01-01 12:20

Additionally, if it's a folder to be removed and it's subsequent child folders or files, use:

git rm -r foldername
查看更多
有味是清欢
6楼-- · 2019-01-01 12:21

Another way if you want to delete the file from your local folder using rm command and then push the changes to the remote server.

rm file1.txt

git commit -a -m "Deleting files"

git push origin master
查看更多
墨雨无痕
7楼-- · 2019-01-01 12:22

This is the only option that worked for me.

git filter-branch -f --index-filter 'git rm --cached --ignore-unmatch *.sql'

Note: Replace *.sql with your file name or file type. Be very careful because this will go through every commit and rip this file type out.

查看更多
登录 后发表回答