On Sunday, March 17, 2013 01:09:47 AM William Park wrote: > On Sat, Mar 16, 2013 at 10:15:50PM -0400, Chris F.A. Johnson wrote: > > On Sun, 17 Mar 2013, Chris Down wrote: > > > ExprCount() { > > > for (( i = $1 ; i > 0 ; i-- )); do > > > : > > > done > > > echo "$1 iterations" > > > } > > > > Or, in a POSIX-compliant manner: > > > > ExprCount() { > > i=$1 > > while [ $(( i -= 1 )) -ge 0 ]; do > > : > > done > > echo Just did $1 iterations using expr math > > } > > Are you saying that > > for (( ; ; )) > > is not POSIX?
Not only is it not POSIX, but it's rather uncommon (bash, zsh, ksh93 only), which is unfortunate because writing the exact equivalent using ''while'' and (()) alone is quite ugly. Usually I put my loops within functions, so the variable initialization part is handled by a typeset that's needed anyway. Certain other aspects are not so easy to emulate cleanly, for instance, preventing a redundant increment on the last iteration, and avoiding an increment on the first iteration. All the workarounds kind of suck. The very best alternative to for ((;;)) is to try and work in a $(()) somewhere in the loop body and do an increment at the same time. function f { typeset n=$1 # localize + initialize while (( n )); do # end condition # cmds... cmd $((n--)) # Hope that there's a convienient spot for $(()) done } This construct at least extends the portability to pdksh and probably a few others. I usually draw the line at shells that lack typeset and inform people to upgrade to something modern. -- Dan Douglas