Linux command to delete all files except .git folder?

后端 未结 6 625
别跟我提以往
别跟我提以往 2020-12-15 03:46

I want to delete all of the current directory\'s content except for the .git/ folder before I copy the new files into the branch.

相关标签:
6条回答
  • 2020-12-15 04:04

    Resetting the index is cheap, so

    git rm -rf .
    git clean -fxd
    

    Then you can reset the index (with git reset) or go straight on to checking out a new branch.

    0 讨论(0)
  • 2020-12-15 04:18

    One way is to use rm -rf *, which will delete all files from the folder except the dotfiles and dotfolders like .git. You can then delete the dotfiles and dotfolders one by one, so that you don't miss out on important dotfiles like .gitignore, .gitattributes later.

    Another approach would be to move your .git folder out of the directory and then going back and deleting all the contents of the folder and moving the .git folder back.

    mv .git/ ../
    cd ..
    rm -rf folder/*
    mv .git/ folder/
    cd folder
    
    0 讨论(0)
  • 2020-12-15 04:22

    As Crayon mentioned in the comments, the easy solution would be to just move .git out of the directory, delete everything, and then move it back in. But if you want to do it the fancy way, find has got your back:

    find -not -path "./.git/*" -not -name ".git" | grep git
    find -not -path "./.git/*" -not -name ".git" -delete
    

    The first line I put in there because with find, I always want to double-check to make sure it's finding what I think it is, before running the -delete.

    Edit: Had a braindead moment, didn't just copy from my terminal.

    Edit2: Added -not -name ".git", which keeps it from trying to delete the .git directory, and suppresses the errors. Depending on the order find tries to delete things, it may fail on non-empty directories.

    0 讨论(0)
  • 2020-12-15 04:24

    With find and prune option.

    find . -path ./.git -prune -o -exec rm -rf {} \; 2> /dev/null
    


    Edit: For two directories .git and dist

    find . -path ./.git -prune -o \( \! -path ./dist \) -exec rm -rf {} \; 2> /dev/null
    
    0 讨论(0)
  • 2020-12-15 04:26
    for i in `ls | grep -v ".git"` ; do rm -rf $i; done; rm .gitignore;
    

    the additional rm at the end will remove the special .gitignore. Take that off if you do need the file.

    0 讨论(0)
  • 2020-12-15 04:26

    should find all the files and directories that with the name .git

    find .  -name .git
    

    should find all the file and directories not named .git

    find . -not -name .git
    

    delete all the files that you find

    find . -not -name .git -exec rm -vf {} \;
    

    be sure that the find is doing what you want

    if you want to delete directories change the rm command to rm -rvf I include the v option to see the files that are deleted.

    if you want to make sure about the files before you delete them pipe the find command to a file and review the results

    0 讨论(0)
提交回复
热议问题