by cdrt · 2y ago · 0 comments
f='a b c d e'
for i in "$f"; do echo $i; done
# prints a b c d e
f="a b c 'd e'"
for i in $f; do echo $i; done
# prints
# a
# b
# c
# 'd
# e'
f=(a b c 'd e')
for i in "${f[@]}"; do echo $i; done
# prints
# a
# b
# c
# d eNormally on the command line data comes from somewhere. It might be some sort of text processing such as a grep or sed command. And that works just fine:
for i in "$(grep stuff)"; do
works just fine and as expected. But when you have to slice and dice that output to fit bash arrays, you not only have to take IFS into account, it quickly gets way harder to read than doing it the normal way. That's why I generally tend to view the use of arrays as a warning. Maybe you are doing something unnecessarily complicated, maybe you are writing Python in bash.Your specific example should be written as the easiest form:
for i in a b c "d e"; do echo $i; done
which does precisely what it looks like.