RandomCoder
RandomCoder

Reputation: 99

Populate an array with list of directories existing in a given path in Bash

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!

Upvotes: 1

Views: 5306

Answers (3)

Aldahunter
Aldahunter

Reputation: 658

Try:

baseDir="/my/directory/path/"
readarray -d '' arr < <(find "${baseDir}" -mindepth 1 -maxdepth 1 -type d -print0)

Here the find command outputs all directories within the baseDir, then the readarray command puts these into an array names arr.

You can then work over the array with:

for directory in "${arr[@]}"; do
    echo "${directory}"
done

Note: This only works with bash version 4.4-alpha and above. (See this answer for more.)

Upvotes: 1

Gordon Davisson
Gordon Davisson

Reputation: 125898

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.

Upvotes: 7

pjh
pjh

Reputation: 8134

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

Upvotes: 3

Related Questions