5

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
2
  • If there's a second array, you could just do echo ${array2[$j]}; j=$((j+1)). Commented Mar 9, 2021 at 21:49
  • BTW, remember to quote your variables unless you have a good reason not to. Commented Mar 9, 2021 at 21:52

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.