Quote:
Originally Posted by
bakunin
The problem is that expanding an array like "${array[*]}" might lead to a line that is longer than "MAXLINE" and/or consisting of more elements than "MAXARGS" allows for.
I'm assuming that by MAXLINE you mean LINE_MAX and that MAXARGS refers to ARG_MAX. In the case of expanding a for-loop's list, neither is relevant.
ARG_MAX limits the size of the command line and environment accepted by the execve system call. The for-loop does not execve the contents of the array; instead, it creates a list and consecutively binds each member to the same identifier.
LINE_MAX is the longest allowable line length (including the terminating newline character) in a text file. Expanding an array into a for-list using
"${arr[@]}" does not generate a line or string. That double-quoted parameter expansion, like its positional parameter counterpart,
"$@", directly generates a list.
I don't think it's germane, but while we're on the subject of LINE_MAX and sh,
POSIX sh exempts shell scripts from this limit:
Quote:
INPUT FILES
The input file shall be a text file, except that line lengths shall be unlimited.
Historical shells may indeed have hardcoded limits, but I suspect that any shell that supports arrays is sufficiently modern to utilize dynamic memory allocation. Virtual memory is almost certainly the actual limit.
I am not advocating against a while-loop. I have nothing against them. Some of my closest friends are while-loops. My point is simply that categorically advising against a for-loop is a bit much; given a modern shell and sufficient memory, the likelihood of a for-loop meltdown is nil.
There also exists the (remote) possiblity that the for-loop mentioned in the OP is the C-like variant supported by ksh93 and bash, which would allow array traversal using a simple index.
Regards,
Alister