0

I want to make a list of all files in a directory and it's subdirectories with a bash script but my array is always empty. I run my script with bash version 4 in Ubuntu 18.04.1. Here is my code:

#!/bin/bash

FILES=()

find ./* -maxdepth 10 -type f  | while read file;
do
    echo $file
    FILES+=("$file")
done

echo "${FILES[@]}"

Thank you.

mirzanahal
  • 167
  • 2
  • 12
  • Your find command appears wrong. Try running with `set -euo pipefail`. But note that find’s first parameter should be a single directory, not several (I believe). – D. Ben Knoble Jan 26 '20 at 16:09
  • `find` can search multiple directory hierarchies. – chepner Jan 26 '20 at 16:10
  • Thank you for your reply. I don't understand why find is the problem when the next command "echo" works perfectly! @chepner – mirzanahal Jan 26 '20 at 16:21
  • Thank you. Still not working. @D.BenKnoble – mirzanahal Jan 26 '20 at 16:21
  • `"${FILES[@]}"` expands to the empty string if `FILES` is not defined, which it is not in the *outer* shell. – chepner Jan 26 '20 at 16:26
  • `FILES=()`, by the way, does not define a variable; it only sets the array attribute on the name `FILES`. The parameter is not set until you add an element to the array. – chepner Jan 26 '20 at 16:27
  • Do you mean I should use `declare -a FILES`? If you do, it doesn't work either. @chepner – mirzanahal Jan 26 '20 at 16:40
  • I still don't know how this is working but I declare a variable `files='find ./* -maxdepth 10 -type f'` and pass it through my while and it's working now. Thank you @chepner – mirzanahal Jan 26 '20 at 17:26

0 Answers0