Skip to content
Advertisement

How to add number assigned as array

I have that script that is supposed to read data from two txt files and add them. For that matter I have used array.

I can read the data but there is a problem with the addition.

JavaScript

Instead of ${dataAll[$i]}= $( ${data1[$i]}+${data2[$i]} ), I have also used 'expr ${data1[$i]}+${data2[$i]}' The analysisSBM105.out file has the following

JavaScript

But still it doesn’t work. The error is

JavaScript

Desired output is the following.

JavaScript

Advertisement

Answer

Bash is space aware. Variable assignment has a = character with no spaces before nor after it.

JavaScript

while I guess you wanted to do:

JavaScript

Notes:

  • declare -a array is not needed. You can just use dataAll[0]=something straight away.
  • it’s easier to write for ((i=0;i<4;++i)) then i=0;while [ "$i" -le 4 ]; do something; i=$((i+1)); done. Also you may for i in $(seq 4)
  • Indent your code properly.
  • Use http://shellcheck.net to check your code
  • The array[<here>] – the <here> part runs as a arithmetic expression, that means that variables are automatically expanded. dataAll[$i] is equal to dataAll[i]. The same happens inside $((..))$(( ${dataAll[$i]} )) is equal to $(( dataAll[$i] )) or just $(( dataAll[i] ))
  • Print array on separate newlines with just printf "%sn" "${dataAll[@]}".
  • You may want to rewrite it in awk for speed and efficiency
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement