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.

#!/bin/bash
n=1
declare -a data1
while read data1
do
data1[$n]=$data1
n=$(( n+1 ))
done <analysisSBM105.out
echo ${data1[1]}
echo ${data1[2]}
echo ${data1[3]}
echo ${data1[4]}

m=1
declare -a data2
while read data2
do
data2[$m]=$data2
m=$(( m+1 ))
done <analysisSBM105.out
echo ${data2[1]}
echo ${data2[2]}
echo ${data2[3]}
echo ${data2[4]}

i=1
declare -a dataAll
while [ $i -le 4 ];
do
${dataAll[$i]}= $( ${data1[$i]}+${data2[$i]} )


i=$(( i+1 ))

done

echo ${dataAll[1]}
echo ${dataAll[2]}
echo ${dataAll[3]}
echo ${dataAll[4]}

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

6436
4167
1933
164
172

But still it doesn’t work. The error is

6436
4167
1933
164
6436
4167
1933
164
Report105.sh: line 35: dataAll[1]: command not found
Report105.sh: line 35: dataAll[2]: command not found
Report105.sh: line 35: dataAll[3]: command not found
Report105.sh: line 35: dataAll[4]: command not found


Desired output is the following.

12872
8334
3866
328
344

Advertisement

Answer

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

${dataAll[$i]}= $( ${data1[$i]}+${data2[$i]} )
                   ^^^^^^^^^^^^^^^^^^^^^^^^^   - command to run
                ^^                           ^ - command substitution, runs command inside
               ^                               - space after `=` - it's not assignment
^^^^^^^^^^^^^^^                                - runs a command named that after expansion

while I guess you wanted to do:

dataAll[i]=$(( data1[i] + data2[i] ))
               ^^^^^^^^^^^^^^^^^^^    - expression to calculate, `${..}` is not needed
           ^^^                     ^^ - arithemtic expansion   
          ^                           - no spaces around =
^^^^^^^^^^                            - variable name

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