The core of this question is answered in the one I marked as a duplicate. Here are a few more pointers:
- All uppercase variable names are discouraged as they are more likely to clash with environment variables.
- You assign to
DIRECTORYS
(should probably be "directories") the output of a complicated command, which suffers from a few deficiencies:
- Instead of backticks as in
var=`command`
, the syntax var=$(command)
is preferred.
egrep
is deprecated and grep -E
is preferred.
- The grep and awk commands could be combined to
awk /^d/ '{ print $8 }'
.
- There are better ways to get directories, for example
find
, but the output of find
shouldn't be parsed either.
- You shouldn't process the output of
ls
programmatically: filenames can contain spaces, newlines, other special characters...
DIRECTORYS
is now just one long string, and you rely on word splitting to iterate over it. Again, spaces in filenames will trip you up.
DIR
isn't declared local
.
- To increase
i
, you'd use (( ++i ))
.
CONTENT[i]=${DIR}
is actually okay: the i
is automatically expanded here and doesn't have to be prepended by a $
. Normally you'd want to quote your variables like "$dir"
, but in this case we happen to know that it won't be split any further as it already is the result of word splitting.
- Array indices start at zero and you're skipping zero. You should increase the counter after the assignment.
- Instead of using a counter, you can just append to an array with
content+=("$dir")
.
- To print the contents of an array, you'd use
echo "${CONTENT[@]}"
.
But really, what you should do instead of all this: a call DirContent some_directory
is equivalent to echo some_directory/*/
, and if you want that in an array, you'd just use
arr=(some_directory/*/)
instead of the whole function – this even works for weird filenames. And is much, much shorter.
If you have hidden directories (names starts with .
), you can use shopt -s dotglob
to include them as well.