mohammad reza
mohammad reza

Reputation: 109

How to store the list of subdirectories into an array and access them by their index in Bash?

Assume That we have a directory name "A" with 4 sub directories(aa,bb,cc,dd), some of the sub directories also have sub directories, so assume a schematic like below:

  A
      aa
           aaa
      bb
           bbb
           bbbb
      cc
      dd

I tried to list the sub directories(aa,bb,cc,dd) in an array and then use them in my script by their array number. I used the script below for copying dd to parent directory:

while IFS= read -d '' file; do
    A+=( "$file" )
done < <(find . -type d -print0 | LC_ALL=C sort -z)

cp -r  `pwd`/${A[4]}"  `pwd`/..

But the problem is that the script make an array of all of the sub-directories, [aa aaa bb bbb bbbb cc dd] so ${a[4]} = bbb and not dd.

Any idea how to fix it?

Upvotes: 2

Views: 320

Answers (1)

codeforester
codeforester

Reputation: 43039

You can restrict find to just look at the top directory, with the maxdepth option:

find . -type d -print0 -maxdepth 1 | LC_ALL=C sort -z

You can achieve the same thing in a simpler way using a glob:

dirs=(*/)             # store all top level directories into the dirs array
dirs=("${dirs[@]%/}") # strip trailing / from each element of the array

and then

cp -r  "$PWD/${dirs[4]}"  "$PWD/.."
  • Double quotes are needed to prevent word splitting and globbing
  • pwd in backquotes can simply be written as $PWD, which doesn't need to create a subshell

Upvotes: 2

Related Questions