Put all filenames in a directory into an array Put all filenames in a directory into an array unix unix

Put all filenames in a directory into an array


Create an array variable with var=(...). A glob for all the files in the current directory is *. Together:

files=(*)echo "${files[@]}"

You can loop over the array:

for file in "${files[@]}"; do    echo "$file"done

Or access individual elements:

echo "${files[0]}"echo "${files[1]}"echo "${files[2]}"

Note the judicious use of double quotes. Those make sure files with whitespace and other special characters are handled correctly.


Most simple solution is to use:

shopt -s nullglob dotglobfiles=(*)