Warn on poor for loop form

Bug #1713891 reported by mcandre
6
This bug affects 1 person
Affects Status Importance Assigned to Milestone
bash8
New
Undecided
Unassigned

Bug Description

Safe, idiomadic bash-derived scripts should use proper for loop form:

for element in "${somearray[@]}"; do
    echo "$element"
end

This accurately expands the elements in the array once for each loop iteration. Other forms, such as using an asterisk (*) in place of an at (@) result in a single string being created, joining each element by $IFS. I'm not sure what using no double-quotes here would behave like, but it's generally considered bad form to manipulate shell variables without double-quotes.

All bash-derived scripts, such as bash, ash, dash, posh, ksh, ksh93, mksh, and zsh should use this form to operate over array elements. This form also avoids manipulating array indices, which can be opportune for mistakes. Of course, sometimes you need to manipulate indices, so that's not something that bashate should warn on, just unquoting or asterisking variables in a for ... in <thing> ... do ... end context.

So in sum, it would be nice for bashate to encourage safe array manipulation when possible.

Note that POSIX sh does not feature for loops, or even arrays as a type. Those scripts should use while loops and either $# length measurements with shift to manipulate argv as an array structure; or else seq or integer indices to work with numerical sequences. See http://www.etalabs.net/sh_tricks.html for more information on that.

To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.