0

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???
}
2
  • 1
    Don't use single variable tmp Use array instead. Check last code snippetunder quoting in this link Commented Mar 25, 2015 at 6:46
  • Your use of $@ unquoted is clearly wrong. It needs to be in double quotes to have its special meaning, distinct from $* (quoted or unquoted). Commented Mar 25, 2015 at 6:52

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

It's not that difficult to do it in POSIX shell: something like [ "$#" -eq 0 ] && exit; i=$#; set -- "$@" -false; while [ "$i" -gt 0 ]; do s=$1; shift; set -- "$@" -o -path "$s"; i=$((i-1)); done; find . \( "$@" \) -prune.
@gniourf_gniourf Hey, you should post that as an answer.
No… there's nothing conceptually different from your answer (which is the correct answer and that I upvoted). You may include it in yours, or leave it as a comment for future reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.