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. – muru Oct 05 '15 at 20:24-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. – mcocdawc Oct 05 '15 at 20:36eval
? Also,find
has a-delete
command. – muru Oct 05 '15 at 20:43-maxdepth 1
for more security. Since the double substitution is not necessary anymore it is even bash compatible now I think. – mcocdawc Oct 05 '15 at 20:52find
. An example: http://paste.ubuntu.com/12692155/ – muru Oct 05 '15 at 21:00-delete
option. Sincefind
also searches in sub directories the safest way was to also include-maxdepth 1
? – mcocdawc Oct 05 '15 at 21:37-maxdepth 1
, but if that's really the case, then you should just use terdon's solution. – muru Oct 05 '15 at 21:39find
for this at all :)find
is rarely the best tool for the job when you don't want recursion. – terdon Oct 05 '15 at 21:39