brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: quote "${files[@]}" so bash keeps names with spaces in one piece

Bash
~/tips/tip-bash-quote-array-expansion

files=("my file.txt" notes.md)

Expand an array without breaking elements that contain spaces.

Arrays are the right way to hold a list of file names in bash. The benefit disappears the moment you expand one without quotes.

Compare three ways to expand the same array:

files=("my file.txt" notes.md)
printf '[%s]' ${files[@]};   echo   # [my][file.txt][notes.md]
printf '[%s]' "${files[@]}"; echo   # [my file.txt][notes.md]
printf '[%s]' "${files[*]}"; echo   # [my file.txt notes.md]

Only the quoted [@] form gives every element as its own argument. Unquoted, bash splits each element on spaces and also expands wildcards in them, so my file.txt becomes two names that do not exist. The [*] form glues everything into one string.

So a copy of the whole list looks like this:

cp -- "${files[@]}" /mnt/backup/

I’d treat "${name[@]}" as a single unit that you never type without its quotes. ShellCheck warns about the unquoted form as SC2068, which catches the cases you miss. "${files[*]}" still has its use when you want one string, like a log line, and it joins with the first character of IFS, normally a space.

Further reading: Bash manual: Arrays, ShellCheck SC2068

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link