As part of a larger script, I am trying to loop through an array of directories to apply a single linux find command. I am trying to make 1 single call to find because I want to pipe the output to some other commands.
Attempt 1 - Without escaping quotes:
# No escape
COLORS=('purple' 'royal blue')
FIND_ARGS=
for C in "${COLORS[@]}";
do
echo "C is $C"
FIND_ARGS+="'${C}' "
done
echo "Arguments for find: $FIND_ARGS"
find $FIND_ARGS -type f ## I even tried putting $FIND_ARGS in quotes here but that acts like a single file
## OUTPUT:
# C is purple
# C is royal blue
# Arguments for find: 'purple' 'royal blue'
# find: '\'purple\'': No such file or directory
# find: '\'royal': No such file or directory
# find: 'blue\'': No such file or directory
With Escapes:
FIND_ARGS=
# With Escape
for C in "${COLORS[@]}";
do
echo "C is $C"
FIND_ARGS+="\'${C}\' " ## Changed original code here to include escapes
done
echo "Arguments for find: $FIND_ARGS"
find $FIND_ARGS -type f
## OUTPUT:
# C is purple
# C is royal blue
# Arguments for find: \'purple\' \'royal blue\'
# find: '\\\'purple\\\'': No such file or directory
# find: '\\\'royal': No such file or directory
# find: 'blue\\\'': No such file or directory
Simple working command run from bash prompt:
## Working Template:
find "purple" "royal blue" -type f
# Output:
# All files in both directories
I am pretty new to bash scripting. Is there a special way that I should be calling this? I looked at the man page for find to see if there is a flag that I need to set, but its rather large, so I could have easily missed it.
Resolution There is no need for the loop. The shell works with the array itself:
find "${COLORS[@]}" -type f