Place each script argument into item once while preserving arguments that contain spaces.
Which for loop is appropriate?
for item in "$@" iterates over each original argument; quote the loop variable when passing it onward.
Detailed explanation
for item in "$*"; do process "$item"; doneIncorrect. "$*" joins all arguments into one value, so the loop runs once.
Incorrect. "$*" joins all arguments into one value, so the loop runs once.
for item in $@; do process "$item"; doneIncorrect. Unquoted $@ can split arguments and expand pathnames.
Incorrect. Unquoted $@ can split arguments and expand pathnames.
for item while "$@"; do process "$item"; doneIncorrect. This is not valid for-loop syntax.
Incorrect. This is not valid for-loop syntax.
for item in "$@"; do process "$item"; doneCorrect. Each positional parameter is assigned to item separately.
Correct. Each positional parameter is assigned to item separately.
Try it yourself
An example you can run in a temporary verification environment.
bash --noprofile --norc -c 'for item in "$@"; do printf "<%s>\n" "$item"; done' demo 'two words' tailExpected result
<two words>と<tail>の2行Key points
- for iterates words
- "$@" preserves boundaries
- Quote the loop variable
Notes
- Environment: GNU Bash 5.2 / 短命シェル
- Command output formatting can vary slightly by distribution or tool version.
- Run the example in a temporary directory or process when possible.
Foundation review
Read the scope first
Check whether the command acts on the current shell, a new process, an existing process, or a file.
Verify the observable result
Use the supplied command and compare the output with the expected result.