the find command is:
find ./ ( -path dir_a -o -path dir_b ) -prune
I want to convert to:
./find.sh dir_a dir_b
so my code (is doesn’t work):
function myfind() { num=1 tmp="" for i in $@ do tmp="$tmp -path './$i' " if [ $((num++)) -ne $# ] then tmp="${tmp} -o" fi done echo $tmp # this is ok!! find ./ ( $tmp ) -prune # is doesn't work, why??? }
Advertisement
Answer
What you are attempting cannot be solved in the general case with “classic sh
” because you need your script to work correctly with directories named *
or '"[ ]"'
, and plain old flat strings simply don’t allow that to be properly quoted (easily, or even with a fair amount of complexity). Fortunately, as suggested in a comment, Bash arrays allow you to do this with all the necessary level of control. Just make sure to always use quotes around anything which could contain a file name.
#!/bin/bash dir_args=() oh= for i; do dir_args+=($oh '-path' "$i") oh='-o' done find . ( "${dir_args[@]}" ) -prune