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.
for file in './*.log'; do printf '%s\n' "$file"; doneIncorrect. 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.
while file in ./*.log; do printf '%s\n' "$file"; doneIncorrect. 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
Shell function
A reusable group of commands that runs in the caller's shell context.
Positional parameter
A numbered argument or special value supplied to a script or function.
Control flow
Conditions, loops, and exit statuses determine which shell commands run.