Process every .log file in the current directory.
Quote the filename when printing it.
Which statement is appropriate?
for file in ./*.log expands the glob to matching paths. Quote the file variable so each path remains one argument.
Detailed explanation
for file in ./*.log; do printf '%s\n' "$file"; doneCorrect. Each glob match is assigned to file and then printed as one quoted argument.
Correct. Each glob match is assigned to file and then printed as one quoted argument.
for file in './*.log'; do printf '%s\n' "$file"; doneIncorrect. Quoting the glob prevents pathname expansion and processes literal text.
Incorrect. Quoting the glob prevents pathname expansion and processes literal text.
for file = ./*.log; printf '%s\n' "$file"Incorrect. The for syntax and do/done body are incomplete.
Incorrect. The for syntax and do/done body are incomplete.
while file in ./*.log; do printf '%s\n' "$file"; doneIncorrect. while does not iterate a glob list in this form.
Incorrect. while does not iterate a glob list in this form.
Try it yourself
An example you can run in a temporary verification environment.
bash -c 'd=$(mktemp -d); touch "$d/a.log" "$d/b file.log"; cd "$d"; for file in ./*.log; do printf "%s\n" "$file"; done; rm -rf "$d"'Expected result
./a.logと./b file.logを1行ずつ表示Key points
- Leave the glob unquoted
- Quote variable expansions
- Preserve filenames containing spaces
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.