Trace Shell Expansion With Filenames That Contain Spaces
Compare quoted and unquoted shell expansions using harmless fixture filenames and verify how each version passes arguments.
Difficulty Beginner
Prerequisites
Use Bash on a Linux workstation in a new practice directory. The script creates two empty local files. Use a fresh directory so you can recognise the output.
Compare the argument lists
mkdir shell-space-practice
cd shell-space-practice
touch -- 'day one.txt' 'day two.txt'
filename='day one.txt'
printf '<%s>\n' "$filename"
printf '<%s>\n' $filename
printf '<%s>\n' ./*.txt
The quoted variable reaches printf as one argument. The next command splits the unquoted substitution on spaces, so printf prints two lines. The glob on the last line expands to two filenames, each retained as a single argument, including its embedded space.
Apply the distinction
for path in ./*.txt; do
printf 'file: %s\n' "$path"
done
The glob must be left unquoted to match files. Inside the loop, quoting the variable preserves the chosen path. Prefixing the pattern with ./ makes a filename that starts with a dash easier to pass safely. Utilities that support an end-of-options marker accept -- before positional filenames.
Troubleshooting and practice
With Bash's default settings, an unmatched glob can remain literal. In a Bash-specific script, consider shopt -s nullglob if an empty result should produce no iterations. Test an unmatched pattern in this practice directory and add a filename containing square brackets. Observe that quoting the variable prevents a second round of filename expansion. Avoid using these exercises with commands that delete files.