0

I have a need for recursively looking through a directory and pass all files with a certain extension to a script. In addition it also takes some optional command lines arguments from the user. To put it all together, I did this

usage="blah" while [ "$1" != "" ]; do case $1 in -arg1 ) shift arg1=$1 ;; -arg2 ) shift arg2=$1 ;; * ) echo $usage exit 1 esac shift done find . -name "*.ext" -exec bash -c 'command "$0" arg1="${arg1:-default}" arg2=${arg2:-default}' "{}" \+ 

However this runs the 'command' command and only passes one file in. How do I get to send the list of files as an argument as well as keep the command line arguments?

EDIT: The command should run only once for the list of matched files.

3
  • 1
    BTW, quoting the {} in find ... -exec ... {} + is only needed for zsh, and the + doesn't need to be quoted at all. Commented Jan 20, 2016 at 21:07
  • Does using "$@" and - {} do what you want? Does argument order between the find-provided arguments and arg1/arg2 matter? Commented Jan 20, 2016 at 21:44
  • ...as another aside, command is an actual shell builtin, so when you use it, folks have to figure out from context whether you actually mean command or if it's a placeholder. Consider something like mycommand or yourcommand in examples instead. Commented Jan 20, 2016 at 21:50

1 Answer 1

1

You don't need bash -c here at all!

find . -name '*.ext' \ -exec yourcommand arg1="${arg1:-default}" arg2="${arg2:-default}" {} + 

See edit history for a discussion of exactly how the old version was broken and how to do more targeted fixes for cases when you really do need a shell.

Sign up to request clarification or add additional context in comments.

3 Comments

Forgot to mention one thing - I want to supply all files and run the command just once. Not run it once per file.
Ahh, gotcha. If the list is too long that actually might not be possible -- like xargs (or any other program on UNIX), find -exec ... {} + can't put more entries on a command line that will fit in ARG_MAX. However, that makes your question much easier. :)
the @$ tip is very handy. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.