Glob expansion in arrays

Arrays are especially useful when used to contain expanded globs:

bash$ myhomefiles=("$HOME"/*)
bash$ printf '%s\n' "${myhomefiles[@]}"
/home/bashuser/code/home/bashuser/docs
/home/bashuser/music
/home/bashuser/Important Notes.txt
/home/bashuser/**README**

The myhomefiles array defined here contains a list of all files and directories matched by the * glob in our home directory, and stores them safely, even if they contain special characters, such as spaces, asterisks, or even newlines.

If you wish to store arguments for a command to execute later or for a script to iterate through, you should always use arrays (or positional parameters with set --). Never try to separate the files out from a single variable afterwards, ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.