-1

I am trying to use multiple for loops to iterate over files with folders within a single folder Eg: Main -> multiple Folders -> Multiple files within folder I am trying to iterate over those files I have written bash script to do so, But I cannot parse variable in the find function, I was wondering is there an easy way to do so,

ApisExternal=$(find main -maxdepth 1 -type d)
for $spaces in $ApisExternal
do
  $ApiSpaces= $(find $spaces -maxdepth 1 -type f)
  for ApiFixValidationError in $ApiSpaces
  do
    echo $ApiFixValidationError
  done
done

This throws an error: `$spaces': not a valid identifier

How can I use the variable as a path for the nested for loop find function. I would appreciate any help with this.

Dhaval Patel
  • 21
  • 1
  • 6

2 Answers2

0

The following should work:

for spaces in $ApisExternal
do
  $ApiSpaces=$(find $spaces -maxdepth 1 -type f)
  for ApiFixValidationError in $ApiSpaces
  do
    echo $ApiFixValidationError
  done
done

If you know certain things about the file hierarchy, it's likely you could workaround the need for a nested loop. E.g.:

  for f in $(find main -path '*some_path*' -a -name '*some_file_name*')
  do
    echo $f
  done

Another example with with compound conditions:

  for f in $(find main -path '*some_path*' -a \( -name '*foo' -o -name 'bar*' \) )
  do
    echo $f
  done

finds all files where the full path contains some_path (-path '*some_path*') and either ends with a file name of foo (-name '*foo'), or starts with bar (-name 'bar*').

And, could probably get rid of the for loop altogether too:

find main -path '*some_path*' \
    -a \( -name '*foo' -o -name 'bar*' \) \
    -exec echo {} \;

... where {} is the file path

Alex
  • 34,899
  • 5
  • 77
  • 90
0

You could do this to avoid issues with files/directories having a space in their names:

for dir in main/*; do
  [[ -d "$dir" ]] || continue     # skip if not directory
  for file in "$dir/*"; do
    [[ -d "$file" ]] && continue  # skip if not a regular file
    # do your stuff with the file
  done
done
codeforester
  • 39,467
  • 16
  • 112
  • 140