|
|
|
|
|
by cdrt
929 days ago
|
|
Your example proves that not using arrays is worse. That loop will only run once and just print every element on one line. The array equivalent works as expected , _isn't_ affected by IFS, and can handle spaces in individual elements 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 e
|
|
Normally 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:
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:
which does precisely what it looks like.