Bash Wildcards – Best Way to Expand Glob Pattern

bashwildcards

I need to expand a glob pattern (like ../smth*/*, or /etc/cron*/) into a list of files, programmatically. What would be the best way to do it?

Best Answer

Just let it expand inside an array declaration's right side:

list=(../smth*/)          # grab the list
echo "${#list[@]}"        # print array length
echo "${list[@]}"         # print array elements
for file in "${list[@]}"; do echo "$file"; done  # loop over the array


Note that the shell option nullglob needs to be set.
It is not set by default.
It prevents an error in case the glob (or one of multiple globs) does not match any name.

Set it in bash with

shopt -s nullglob

or in zsh with

setopt nullglob