Adding Two Array in shell script

Hi Experts,

I've got this problem where I need to add two array in shell script such that that is an element is greater than 9 then it get further split into individual digit, something like below :

Input :-
array1=(2 6 8 9 10 12)
array2=(5 4 6 8 12 14)
Output :-
array3=(7 1 0 1 4 1 7 2 2 2 6)

Explanation :- 5+2 = 7   (less then 10 so no action required)
                    6+4 = 10 (greater then 9 so it gets split into 1,0)

Here is what I've tried to add two array which is working fine but not sure on how to split the number.

#!/bin/bash
welcome()
{
echo "Welcome to first array progg."
}
main_logic()
{
 declare -a arr1=(5 7 9 12 14 19)
 declare -a arr2=(7 4 3 8 12 17)
 declare -a arr3=()
 sum=0
 len=${#arr1[@]}
 for ((i=0; i<$len; i++))
 do
     sum=$(( ${arr1[$i]}+${arr2[$i]} )) 
     #echo $sum
     arr3=("${arr3[@]}" "$sum")
 done 
echo ${arr3[@]}
}
##Entry Point of the Progg.
welcome
main_logic
     sum=$(( ${arr1[$i]}+${arr2[$i]} ))       #echo $sum
     if [ $sum -gt 9 ]
     then
       arr3=("${arr3[@]}" "$sum/10") #sum divided by 10
       arr3=("${arr3[@]}" "$sum%10") #mod 10 sum
     else
       arr3=("${arr3[@}" "$sum")
      fi

I don't normally use bash or arrays, so I am sure of the syntax.
Will there be a possibility that the sum is greater than 99?

How about

for i in ${!array1[@]}; do printf "%s" $((array1 + array2)); done | od -An -c
   7   1   0   1   4   1   7   2   2   2   6
1 Like

Thanks Rudic,

Can you please also explain the logic used in below part :

od -An -c

man od :

Thanks Rudic,

Really liked the way you did it, very short and crisp. Just wondering if there is way to achieve it via sed or some other array operation.

Why sed specifically? Is this homework?

Shell doesn't really have "array operations", just loops.

There are no array operations for the not-that-common things you want to do. You'll need to take the scenic route, as did jgt, if you don't play tricks.

If you just need an array to hold the result, slip in a pair of parentheses, and there you are:

array3=($(for i in ${!array1[@]}; do printf "%s" $((array1 + array2)); done | od -An -c))
echo ${#array3[@]}
11
echo ${array3[6]}
7
1 Like

Hi.

If you allow sed and od , then why not awk , perl , c , R , Swift , Rust , go , tcl(sh) etc.?

Best wishes ... cheers, drl