bash shell array – How to Pass Parameters to a Program Using a Bash Variable

arraybashfedorashell

I'm trying to clean up my shell script by placing repeating parameters in a bash variable.

The best approach I know is to put it in an array and pass it… but that doesn't seem to work. How can I store all the parameters in a variable?

This doesn't work:

TESTP=( "-path" "\"./var/*\"")
echo ${TESTP[@]}
 # Results in: -path "./var/*"
find ${TESTP[@]}
 # Returns no results.

While find -path "./var/*" does return all files under var.

Best Answer

You either want to pass those array elements as arguments to find:

TESTP=(-path './var/*')
find . "${TESTP[@]}"

Or build a shell command line and ask the shell to interpret it (and the quotes in it):

TESTP='-path "./var/*"'
eval "find . $TESTP"

Or you could use the split+glob operator (which you inappropriately used by leaving your variable unquoted in your question) on a scalar variable:

TESTP='-path,./var/*'

set -f # no glob
IFS=,  # split on ,
find . $TESTP

In your,

TESTP=( "-path" "\"./var/*\"")
find ${TESTP[@]}

${TESTP[@]} is first expanded to the array element (-path and "./var/*"), and then each is subject to the split+glob operator (as you forgot to quote it), so with the default value of $IFS, they would not be split, but because the second one contains a wildcard it could be expanded to the files whose name end in " in the "./var directory.

Most likely there's no ". directory, so both arguments are left asis and passed to find. And that would be the same as

find -path '"./var/*"'

That is, looking for files below the "./var directory that end in a " character.

Related Question