Search code examples
bashbc

bash operations on arrays using bc


from reading the man page of bc, it seems that bc can accept simple variables, but also arrays as input.

However, if I try to add two arrays, I only get a single element as an output

a=(1 2 3)
b=(10 11 12)
c=`echo "$a + $b" | bc`

Then c only contains 11. If there a way to get bc to operate on all elements in the arrays to produce (11 13 15) as an output? Or do I need to do a loop?


Solution

  • bc can't natively access bash arrays, but you can generate from your two arrays a stream of addition operations, and read their results back into a third array (thus only needing to invoke bc once, rather than running a separate copy of bc per loop entry):

    a=(1 2 3)
    b=(10 11 12)
    
    readarray -t c < <(for idx in "${!a[@]}"; do
      echo "${a[$idx]} + ${b[$idx]}"
    done | bc)
    declare -p c              # print output as an array definition
    printf '%s\n' "${c[@]}"   # print output one entry per line
    

    See this running at https://ideone.com/YuPhQP, properly emitting as output:

    declare -a c=([0]="11" [1]="13" [2]="15")
    11
    13
    15