2

I am very new to bash and am currently stuck on a small project. I am trying to list the combined scores of each array (num1 and num2) and then display the output using a C-style loop. Here is my desired output:

Result_1: 71
Result_2: 96
Result_3: 101
Result_4: 86
Result_5: 148

As you can see, the first number in the num1 array is added with the first number of the num2 array to form Result_1, and the second number in the num1 array is added with the second number from the num2 array to form Result_2.. and so on. However, I am only able to get and display the sum of the first two numbers (13 and 58 = 71) for all results when this is not what I am after. I also wish to have the first result as "Result_1" instead of "Result_0", but can't seem to figure this out either. This is my current code:

#!/bin/bash

num1=(13 28 11 72 50)
num2=(58 68 90 14 98)
len=${#num1[*]}

for (( i=0; i<${len}; i++ ));
do
    sum=$(($num1 + $num2))
    echo "Result_"$i":" $sum
done

Any help would be greatly appreciated. Thanks!

1 Answer 1

3

You just forgot to link index to array. The following loop will do the correct job.

for (( i=0; i<${len}; i++ ))
do
    sum=$((${num1[$i]} + ${num2[$i]}))
    echo "Result_$(($i+1)):" $sum
done
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.