I have the same problem as this question How to delete all the files/folders from the folder except few folders? several times. This is the reason why I wanted to write myself a script for a command rmnot. It should take an arbitrary number of files even with wildcards if necessary and delete anything (not recursevely) in the same directory except for those files. Typical example would be:
rmnot *tex *bib *png
My script works, but since I am inexperienced and want to learn it the proper way, is there a more elegant way to do write this script?
#!/bin/zsh
insert="-name . -or -name .."
for i in {1..$#}; do
insert="$insert -or -name ${(P)i}"
done
insert="\( $insert \)"
eval "find -not $insert -exec rm {} \;"
PS: I have to use ZSH because of the double substitution ${(P)i}
anything else would work in bash as well I think.
======Optimized Version=====
#!/bin/bash
insert="-name . -or -name .."
for i; do
insert="$insert -or -name $i"
done
insert="\( $insert \)"
find -maxdepth 1 -not $insert -delete
-name . or -name ..
, use-mindepth 1
. You don't need double substitution. Just dofor i; do insert="$insert -or -name $i"; done
. Afor x
without anin
loops over the script arguments.-mindepth 1
option brings new problems because -or forces something to have in front. So I need to defineinsert= something
nevertheless before the loop. Or I need some other lines to chop the -or in front away. But I think this would be over engineering.eval
? Also,find
has a-delete
command.-maxdepth 1
for more security. Since the double substitution is not necessary anymore it is even bash compatible now I think.find
. An example: paste.ubuntu.com/12692155