There are plenty of situations where the use of a *
is virtually inevitable – e.g. rm -rf *
in a folder that holds thousands of subfolders and files.
But what if you want to exclude just one or two files or folders from the rm
command? I've googled my way around and only found quite complicated solutions like find . -depth -not \( -name 'one' -o -name 'two' \
as stated here.
-o -name 'three' \) -exec rm {} \;
Is there a possibility to do this in an easier way – without that detour to find
?
E.g. rm -rf --exclude='one' --exclude='two' --exclude='three' *
like in rsync or just rm -rf -e 'one','two','three' *
?
Maybe even a general possibility to exclude things from *
(so other commands like cp
, mv
, … don't have to implement their own)? Something like *{'one','two','three'}
or so?
Best Answer
For Bash there is a shell option called
extglob
that is deactivated by default to keep compatibility with standard shell syntax. Extglob complements the syntax by additional operators like!()
,?()
,@()
and some more.To switch
extglob
on, typeshopt -s extglob
. To keep it switched on for the current user typeecho 'shopt -s extglob' >> ~/.bashrc
.For the rm example: With
extglob
you can use