How do you loop over files whose names may contain spaces or newlines?
IntermediateConceptArrays, conditionals and loops
Answer
Globs are safe in a for loop because each match becomes exactly one word. For recursive searches use NUL separators:
shopt -s nullglob
for f in /var/log/app/*.log; do gzip -- "$f"; done
find /data -type f -name '*.csv' -print0 |
while IFS= read -r -d '' f; do
process -- "$f"
done
Never parse ls output (SC2012): names with newlines or spaces break it, and ls output is meant for humans.
More on Arrays, conditionals and loops
How do you declare, populate and iterate an indexed array?BeginnerWhat is the difference between `"${arr[@]}"` and `"${arr[*]}"`?IntermediateHow do associative arrays work and what are they good for in DevOps scripts?IntermediateHow do you read a command's output into an array correctly?IntermediateWhat is the difference between `[ ]`, `[[ ]]` and `(( ))`?BeginnerWhy does `[ $var = "prod" ]` fail when `var` is empty or contains spaces?Intermediate