0

I want to write a script that loops through a array and loop will consider current and following values in every round, for example -

VARIABLES=( 10 20 30 40 50 80 )

for i in ${VARIABLES[@]}; do   ## Ideally it should stop at 2nd last value 
        #Value1=$i 
        #Value2=$(i+1)
done 

How to achieve the same in correct way?

0

2 Answers 2

1

I've got few variants, first using function and shift

values=( 10 20 30 40 50 80 )

get_paired_values () {
    while [[ $@ ]]; do
        value1=$1 value2=$2
        echo "$value1 $value2"
        shift 2
    done
}

get_paired_values "${values[@]}"

And second using while loop over indexes, which is even more elegant)

i=0
while [[ ${values[$i]} ]]; do
    value1=${values[$i]}  ; ((i++)); value2=${values[$i]}
    echo "$value1 $value2"; ((i++))
done

And a variation of second method but using slice and read

i=0
while [[ ${values[$i]} ]]; do
    read   value1  value2 <<< ${values[@]:$i:2}
    echo "$value1 $value2"; ((i+=2))
done
Sign up to request clarification or add additional context in comments.

Comments

0

You need to loop through the indexes, not the array elements, so you can do arithmetic with the index.

for ((i=0; i < ${#VARIABLES[@]}-1; i++))
do
    value1=${VARIABLES[i]}
    value2=${VARIABLES[i+1]}
    ...
done

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.