简体   繁体   中英

Bash- add up two arrays variables' to third array's variable

i have three arrays A, B, C . Array AB values are being parsed from file and i want them to add up into array C .

#!/bin/bash
i=0
A=()
B=()
C=()
while read line
do
  A[i]="$(echo $line| cut -d\  -f4)"
  B[i]="$(echo $line| cut -d\  -f11)"
  echo ${A[i]} " and " ${B[i]}
  # outputs correct values
  C[i]=`expr ${A[i]} + ${B[i]}`
  echo ${C[i]} 
  # no output
  i=$((i+1))
done < ~/file
exit 0

what is wrong with that assignment?

complete line from script:

hitEnd[i]=`expr ${hitLength[i]}+${hitStart[i]}`
echo "${hitEnd[i]}"
#no output

the line:

    C[i]=`expr ${A[i]} + ${B[i]}`

while give an error if one of the two operands is missing. If that is expected, ie having empty fields in the files, then:

   C[i]=$((${A[i]:-0}+${B[i]:-0}))

Should work.

The script look correctly. You may not construct the array correctly.

And always double quote the variable to avoid some error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM