A. Gille A. Gille - 1 year ago 74
Bash Question

Parameter expansion not working in "find -exec"

I'm writing a bash script as above, but the parameter expansion is not working with the


EXC="--exclude='*.js' --exclude='*.sh'"
find /path -exec grep ${EXC} "xxx" {} \; >> result.txt

Options in the
variable are not used by the
call as it still parse JavaScript files...

Also tried

find /path -exec grep $EXC "xxx" {} \; >> result.txt

Answer Source

The problem is that the single quotes are not removed from the parameter expansion, so grep is receiving '*.js' as the pattern, not *.js as you want. You need to use an array to hold the arguments:

exc=( "--exclude=*.js" "--exclude=*.sh" )  # No single quotes needed
find /path -exec grep "${exc[@]}" "xxx" {} \; >> result.txt

The quoted parameter expansion prevents *.js and *.sh from being expanded by the shell in the same way that quoting them when used literally does. --exclude='*.js' and '--exclude=*.js' would both result in the same argument being passed to grep, as would the minimalist --exclude=\*.js. You could also define your array as

exc=( --exclude "*.js" --exclude "*.sh" )

since the long option and its argument can be specified as one word containing = or as two separate words.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download