0

How can I delete all directories recursively where the name starts with app-deployment-* except a particular directory with name app-deployment-245a578. I.E. delete all directories using a glob match but don't delete a particular known named directory.

rm -rf app-deployment-* # except app-deployment-245a578
Justin
  • 5,328
  • 19
  • 64
  • 84

1 Answers1

1
find ./ -maxdepth 1 \
        -type d \
        -name 'app-deployment-*' \
        ! -name 'app-deployment-245a578' \
        -exec echo rm -rf {} +

Explanations:

  • -maxdepth 1 mean without recursion;
  • -type d mean search only for directories;
  • -name 'app-deployment-*' is a pattern of directories you are searching for;
  • ! -name 'app-deployment-245a578' is a pattern of directories you are excluding from result list
    Repeat it multiple times if you want to exlude multiple directories;
  • exec echo rm -rf -- execute a command echo rm -rf;
  • {} + -- add search results as a parameters to the command above.
    Directory names will be added like that: echo rm -rf dir1 dir2 dir3.

About the last point. If you want to call the command with each param separately (I mean echo rm -rf dir1; echo rm -rf dir2;), you should write {} \; (note the backslash) instead of {} +.

About the command. I write echo rm -rf instead of rm -rf due to all the danger of using rm -rf with any kind of pattern matching. Be careful and check everything before removing echo from the command.

Futher reading about danger of rm + patterns: Creative uses of rm

UPD: worth noting that {} + should be at the end of command, i.e. you can't use -exec rm {} + -rf