On Sat, Apr 16, 2022 at 04:20:15PM +0800, wilson wrote: > does bash shell have the list/array concept?
Bash has indexed arrays (since forever) and associative arrays (in version 4.0 and above). > ~$ list="1 2 3 4" > > ~$ for i in $list; do echo $i; done > 1 > 2 > 3 > 4 > > is this a list access? That's a string, and an abuse of word-splitting. It's a common anti-pattern used in sh scripts, because sh doesn't have arrays or lists. It "works" in this simple case, and in many other simple cases, where the "list" elements are known-in-advance words that don't contain any whitespace or globbing characters (and can't be the empty string). It completely fails if the list elements contain any of those things. Most notably, when the list elements are filenames, this approach is doomed. Here's how you would do it correctly in bash: list=(1 '' 2 'two and a half' 3 '3.14*' 4) for i in "${list[@]}"; do echo "<$i>"; done The for loop can mostly be replaced by a single printf: printf '<%s>\n' "${list[@]}" But there is one difference: if the array is empty (has zero elements), the printf will still print one time, with an empty string as the argument. The for loop will not print anything at all. See also: https://mywiki.wooledge.org/BashGuide https://mywiki.wooledge.org/BashFAQ/005