How do you store a list of directories into an array in Bash (and then print them out)? How do you store a list of directories into an array in Bash (and then print them out)? arrays arrays

How do you store a list of directories into an array in Bash (and then print them out)?


$ ls -a./ ../ .foo/ bar/ baz qux*$ shopt -s dotglob$ shopt -s nullglob$ array=(*/)$ for dir in "${array[@]}"; do echo "$dir"; done.foo/bar/$ for dir in */; do echo "$dir"; done.foo/bar/$ PS3="which dir do you want? "$ echo "There are ${#array[@]} dirs in the current path"; \select dir in "${array[@]}"; do echo "you selected ${dir}"'!'; break; doneThere are 2 dirs in the current path1) .foo/2) bar/which dir do you want? 2you selected bar/!


Array syntax

Assuming you have the directories stored in an array:

dirs=(dir1 dir2 dir3)

You can get the length of the array thusly:

echo "There are ${#dirs[@]} dirs in the current path"

You can loop through it like so:

let i=1for dir in "${dirs[@]}"; do    echo "$((i++)) $dir"done

And assuming you've gotten the user's answer, you can index it as follows. Remember that arrays are 0-based so the 3rd entry is index 2.

answer=2echo "you selected ${dirs[$answer]}!"

Find

How do you get the file names into an array, anyways? It's a bit tricky. If you have find that might be the best way:

readarray -t dirs < <(find . -maxdepth 1 -type d -printf '%P\n')

The -maxdepth 1 stops find from looking through subdirectories, -type d tells it to find directories and skip files, and -printf '%P\n' tells it to print the directory names without the leading ./ it normally likes to print.


#! /bin/bashdeclare -a dirsi=1for d in */do    dirs[i++]="${d%/}"doneecho "There are ${#dirs[@]} dirs in the current path"for((i=1;i<=${#dirs[@]};i++))do    echo $i "${dirs[i]}"doneecho "which dir do you want?"echo -n "> "read iecho "you selected ${dirs[$i]}"