Brad Parks
Brad Parks

Reputation: 71961

Bash - how to iterate over array in steps of 2?

I'm wondering what's the best way to iterate over an array in steps of 2 or more in bash?

For example the following 2 approaches work, but what's the cleanest/simplest way to do this?

test_loops.sh

#!/usr/bin/env bash

function strategyOne()
{
  X=0
  for I in "$@"
  do
    X=$((X%2))
    if [ $X -eq 1 ]
    then
      B="$I"
      echo "Pair: $A,$B"
    else
      A="$I"
    fi

    X=$((X+1))
  done
}

function strategyTwo()
{
 ARG_COUNT=$#
 COUNTER=0
 while [  $COUNTER -lt $ARG_COUNT ]; do
     let COUNTER=COUNTER+1 
     A="${!COUNTER}"
     let COUNTER=COUNTER+1 
     B="${!COUNTER}"

     if [ $COUNTER -le $ARG_COUNT ]
     then
       echo "Pair: $A,$B"
     fi
 done
         
}

echo
echo "Strategy 1"
strategyOne $*

echo
echo "Strategy 2"
strategyTwo $*

Produces output like so:

$ ./test.sh a b c d e

Strategy 1
Pair: a,b
Pair: c,d

Strategy 2
Pair: a,b
Pair: c,d

Upvotes: 5

Views: 3055

Answers (3)

Maxim Norin
Maxim Norin

Reputation: 1391

One more way to do this:

data=("Banana" "Apple" "Onion" "Peach")
for i in $(seq 0 2 $((${#data[@]}-1)))
do
    echo ${data[i]}
done

Upvotes: 5

Matias Barrios
Matias Barrios

Reputation: 5056

Here you have a simple way in Bash.

#!/bin/bash

data=("Banana" "Apple" "Onion" "Peach")

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

Regards!

Upvotes: 9

anubhava
anubhava

Reputation: 784998

You can use iterate using array index:

arr=( 1 2 3 4 5 6 7 8 9 )

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

1
3
5
7
9

Upvotes: 2

Related Questions