Arrays and loops in zsh

Section 15.2.1 “Array Subscripts” says that arrays can be index with [exp] (where exp is a numeric expression) and that elements start at index 1 (0 if KSH_ARRAYS is set).

Section 14.3 “Parameter Expansion” says that the syntax ${#array_name} will expand to the number of elements of an array.

Section 6.3 “Complex Commands” gives the syntax for a numeric for loop (as in C):
for (( initExpr ; testExpr ; stepExpr )) do … done.

Putting them all together:

for (( i = 1; i <= $#LOCAL_PATH; i++ )) do
    ( # subshell to contain the effect of the chdir
        cd $LOCAL_PATH[i]
        hg pull $REMOTE_PATH[i]
    )
done

Or, if you are using KSH_ARRAYS, then this:

for (( i = 0; i < ${#LOCAL_PATH[@]}; i++ )) do
    ( # subshell to contain the effect of the chdir
        cd ${LOCAL_PATH[i]}
        hg pull ${REMOTE_PATH[i]}
    )
done

Using KSH_ARRAYS makes arrays start with index 0, requires the use of braces for array expressions, and interprets $array as $array[0] (requiring a change to the array length expression). The syntax changes required by KSH_ARRAY will also work without KSH_ARRAY, but you still have to adjust the logic for the different index range (1 through N versus 0 through N-1).

Tags:

Zsh

Array