NewUser
NewUser

Reputation: 53

Loop over two array values at a time

How can I loop over two array values at a time? I tried using a for loop but I could only figure out how to echo one at a time.

#!/bin/bash

array=(value1 value2 value3 value4 value5 value6 value7 value8 value9 value10)

for i in ${array[@]}
do
        echo $i
done

Is there a way to change the for loop that it will echo two values at a time like below?

value1 value2
value3 value4
value5 value6
value7 value8
value9 value10

Upvotes: 5

Views: 183

Answers (1)

John Kugelman
John Kugelman

Reputation: 361585

Looping over indices will be easier than looping over the elements. You can pull out the two elements by index:

for ((i = 0; i < ${#array[@]}; i += 2)); do
    echo "${array[i+0]} ${array[i+1]}"
done

Or you could extract array slices using the syntax ${variable[@]:offset:length}:

for ((i = 0; i < ${#array[@]}; i += 2)); do
    echo "${array[@]:i:2}"
done

This would be especially useful if you wanted more than two elements at a time.

Upvotes: 7

Related Questions