0

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
ama.do
  • 33
  • 4
  • `find "${FIND_ARGS[@]}"`, though you shouldn't be using all caps names for your own variables. – Charles Duffy Jan 19 '21 at 00:54
  • Run your code through http://shellcheck.net/ and read the wiki pages linked for each warning. – Charles Duffy Jan 19 '21 at 00:55
  • The other critical thing is that `FIND_ARGS+="'${C}' "` isn't creating an array at all. – Charles Duffy Jan 19 '21 at 00:56
  • You need to use `find_args+=( "$c" )` to add elements to an array, after initializing it with `find_args=()`; then `"${find_args[@]}"` to expand. – Charles Duffy Jan 19 '21 at 00:56
  • Also see [BashFAQ #50](https://mywiki.wooledge.org/BashFAQ/050) for an expansion of why what you were attempting in the question didn't work (and thus why you need to use arrays instead). – Charles Duffy Jan 19 '21 at 01:03
  • Ahh. I was building a string when I should be just working with the array itself. Thank you very much! I see where I went wrong. – ama.do Jan 19 '21 at 02:00

0 Answers0