1

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?

3
  • 1
    Your assignment will only ever make c a single string. Note that "$a" when a is an array refers implictly to "${a[0]}". Commented Feb 25, 2019 at 13:30
  • bc isn't part of bash, so it can't read internal bash datastructures -- all communication between bash and bc is via generation and parsing of strings. Thus, echo "$a + $b" is generating a single string; bc can't see the original variables and has no way of knowing what their values were. Commented Feb 25, 2019 at 13:31
  • ...thus, bc has support for arrays in the same sense that Python or awk support arrays -- they do, but those arrays have nothing whatsoever to do with bash arrays. Commented Feb 25, 2019 at 13:32

1 Answer 1

5

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
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.