Delete all files and directories but certain ones using Bash

后端 未结 3 1280
抹茶落季
抹茶落季 2020-12-30 07:23

I\'m writing a script that needs to erase everything from a directory except two directories, mysql and temp.

I\'ve tried this:

ls * | grep -v mysql         


        
相关标签:
3条回答
  • 2020-12-30 07:27

    You may try:

    rm -rf !(mysql|init)
    

    Which is POSIX defined:

     Glob patterns can also contain pattern lists. A pattern list is a sequence
    of one or more patterns separated by either | or &. ... The following list
    describes valid sub-patterns.
    
    ...
    !(pattern-list):
        Matches any string that does not match the specified pattern-list.
    ...
    

    Note: Please, take time to test it first! Either create some test folder, or simply echo the parameter substitution, as duly noted by @mnagel:

    echo !(mysql|init)
    

    Adding useful information: if the matching is not active, you may to enable/disable it by using:

    shopt extglob                   # shows extglob status
    shopt -s extglob                # enables extglob
    shopt -u extglob                # disables extglob
    
    0 讨论(0)
  • 2020-12-30 07:45

    This is usually a job for find. Try the following command (add -rf if you need a recursive delete):

    find . -maxdepth 1 \! \( -name mysql -o -name temp \) -exec rm '{}' \;
    

    (That is, find entries in . but not subdirectories that are not [named mysql or named tmp] and call rm on them.)

    0 讨论(0)
  • 2020-12-30 07:45

    You can use find, ignore mysql and temp, and then rm -rf them.

    find . ! -iname mysql ! -iname temp -exec rm -rf {} \;
    
    0 讨论(0)
提交回复
热议问题