2 ms·
> For iterating over an array: Bash array syntax is error prone and hard to read, and the expansion of arrays still depend on the field separator and must fit
by xorcist 3y ago
> For iterating over an array:
Bash array syntax is error prone and hard to read, and the expansion of arrays still depend on the field separator and must fit in the environment.
Most of the time you should just rely on that field separator and do it the simple way:
for i in "$f"; do echo $i; done
Much more obvious and more shell-like. That's how all bash functions process their parameters.
Set IFS only if you really need to. But in that case also consider something like xargs where you are not limited by environment, have null terminated fields, and offer parallelism.
Arrays are only useful when you need multidimensionality, at which point you should probably look at using data files and process with other tools such as sed. Or start looking at something like Perl or Python.
- cdrt 3y agoYour 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
- xorcist 3y agoYou could always construct an example to how a specific behaviour. The problem in the example here is that you can't set environment variables to a list of arguments, you can only set it to text strings. 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: 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.