I am trying to learn loops and array manipulation in zsh.

Say I have two arrays in zsh with the same unknown # of elements and each of them containing a list of paths, e.g.


I would like to iterate through both arrays simultaneously with a common index, so that I can do something like:

hg pull $REMOTE_PATH_i

in each iteration. How can I do this in zsh?

Also, I have searched for loop control and arrays in the zsh documentation but had little success. Is there a good tutorial that introduces the basics of loops, arrays, etc. in zsh? Something for people with little bash or shell-scripting experience but with a background in programming?


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]

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]}

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).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.