David Botezatu
David Botezatu

Reputation: 189

Bash: adding directory names into array

As title says, I want to add directory names into an array, but can't figure it out how. This is what I have so far:

path=some/path/in/linux

declare -a categ_array

for d in ${path}/*; do
    #strip directory name of the path
     dir_name=${d##*/}

     #add the directory name into array
     categ_array+=("${dir_name}")
done

echo ${categ_array}

This code outputs only 1 directory name (doesn't matter how many directories i have).

Upvotes: 1

Views: 144

Answers (1)

anubhava
anubhava

Reputation: 785316

You need to use this command to print all directories:

echo "${categ_array[@]}"

Though you can avoid loop and just use:

cd "$path"
categ_array=()
categ_array+=(*/)

examine the results:

declare -p categ_array

Upvotes: 4

Related Questions