When running `rm -rf`, is it possible to exclude certain subdirectories?
Simple conceptually, and has a low risk of error:
mkdir TO_DELETE
mv * TO_DELETE
mv TO_DELETE/var_opt TO_DELETE/var_log .
rm -rf TO_DELETE
Ignore the error from mv
about moving TO_DELETE
to a subdirectory of itself.
You can also use ksh's extended globs:
rm -rf !(var_opt|var_log)
These are also available in bash if you enable them:
shopt -s extglob
rm -rf !(var_opt|var_log)
Ditto in zsh:
setopt ksh_glob
rm -rf !(var_opt|var_log)
Zsh also has its own extended globs:
setopt extended_glob
rm -rf ^var_(opt|log)
If your input file names are generated by users, you need to deal with surprising file names containing space, ', or " in the filename.
The use of xargs
can lead to nasty surprises because of the separator problem.
GNU Parallel does not have that problem.
find /space ! -iregex '(var_opt|var_log)' | parallel -X rm -f
Watch the intro video for GNU Parallel to learn more.