0

I have a directory path where there are multiple files and directories.

I want to use basic bash script to create an array containing only list of directories.

Suppose I have a directory path: /my/directory/path/

$ls /my/directory/path/
a.txt dirX b.txt dirY dirZ

Now I want to populate array named arr[] with only directories, i.e. dirX, dirY and dirZ.

Got one post but its not that relevant with my requirement.

Any help will be appreciated!

2 Answers2

4

Try this:

#!/bin/bash
arr=(/my/directory/path/*/)    # This creates an array of the full paths to all subdirs
arr=("${arr[@]%/}")            # This removes the trailing slash on each item
arr=("${arr[@]##*/}")          # This removes the path prefix, leaving just the dir names

Unlike the ls-based answer, this will not get confused by directory names that contain spaces, wildcards, etc.

Gordon Davisson
  • 107,068
  • 14
  • 108
  • 138
2

Try:

shopt -s nullglob   # Globs that match nothing expand to nothing
shopt -s dotglob    # Expanded globs include names that start with '.'

arr=()
for dir in /my/directory/path/*/ ; do
    dir2=${dir%/}       # Remove the trailing /
    dir3=${dir2##*/}    # Remove everything up to, and including, the last /
    arr+=( "$dir3" )
done
pjh
  • 4,359
  • 14
  • 15