Array expansion with @ and *
An array is most useful when its elements keep their boundaries. As a standalone double-quoted word, "${items[@]}" expands to one argument per element, including empty strings. An empty array contributes zero arguments. In contrast, "${items[*]}" joins the values into one word using the first character of IFS (a space if IFS is unset, no separator if IFS is empty). Use the joined form only when a single string is intended. Unquoted expansion in ordinary command arguments can split strings and expand filename patterns. Use for item in "${items[@]}" to iterate safely. The examples use positional parameters and shift concepts from Chapter 2 to inspect argument counts; set -- replaces the current script arguments in these disposable examples. For an empty array, standalone quoted "${items[*]}" produces one empty argument in Bash 5.2, whereas "${items[@]}" produces none. When quoted @ is embedded in a larger word, the prefix attaches to the first element and the suffix to the last; use a standalone expansion for straightforward argument forwarding.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Preserve each argument
items=('daily report' '' '*')set -- "${items[@]}"printf 'count=%s\n' "$#"for item; do printf '[%s]\n' "$item"; doneExpected stdout:
count=3[daily report][][*]Three exact arguments survive, including a literal glob character.
Join intentionally
items=('daily report' '' '*')IFS=: printf '[%s]\n' "${items[*]}"Expected stdout:
[daily report::*]The empty middle element produces two adjacent separators.
Zero versus one argument
items=()set -- "${items[@]}"printf 'empty array=%s\n' "$#"items=('')set -- "${items[@]}"printf 'empty element=%s\n' "$#"Expected stdout:
empty array=0empty element=1Zero elements and one empty element are distinct.
Common mistakes
Writing ${items[@]} without quotes can turn one value into several arguments or discard empty values. Quoting the entire expansion with * is not a substitute for preserving individual arguments.
Practice
Create an array of three values: a phrase with spaces, an empty string, and a literal asterisk. Compare the argument counts for quoted @ and quoted *; use IFS=: for joining. Also compare an empty array with an array containing one empty string.
Next: Array append, slice and unset