Build commands with arrays
When assembling a command dynamically, store the executable and every argument in separate array elements. cmd=(printf '%s\n') makes the format a distinct argument. Append data with cmd+=("$value") and invoke "${cmd[@]}". Bash uses the first expanded word as the command name and the rest as arguments. This preserves spaces, empty strings, wildcard characters and text that resembles shell syntax without reparsing it. It does not make arbitrary commands safe: choose a trusted executable and fixed options, validate values where the receiving program expects them, and use -- before operands only for commands that support it. Redirections and pipelines must be written as actual shell syntax outside the array. Do not use eval to execute a joined command string. For a command array, ensure it contains a trusted nonempty command name before invocation. An empty command array expanded by itself can silently execute no command and return status zero. Validate the command choice before invoking it. In example 3, guard the write and read so that a failed operation does not print an apparent result.
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.
Build a format and data
cmd=(printf '[%s]\n')value='daily report.txt'cmd+=("$value" '')"${cmd[@]}"Expected stdout:
[daily report.txt][]The format is fixed, and each data element remains separate.
Syntax-looking data stays data
cmd=(printf '%s\n')cmd+=('a; b' '*' '$(date)' '>')"${cmd[@]}"Expected stdout:
a; b*$(date)>No element is parsed again as a shell operator or substitution.
Use real redirection outside the array
cmd=(printf '%s\n' 'report ready')"${cmd[@]}" > result.txt &&IFS= read -r line < result.txt &&printf '[%s]\n' "$line"Expected stdout:
[report ready]The redirection is shell syntax; the array contains command words only.
Common mistakes
Do not place | or > in array elements expecting shell operators; they become arguments. Avoid eval and never let untrusted input choose the executable or printf format.
Practice
Build a printf command array with a fixed bracket format, append a spaced filename, a literal asterisk and an empty value, then execute it. Redirect the output to a fresh lab file outside the array and inspect the file.
Next: Collect lines into arrays