# Counting and adding if some arrays has element at some index

Can the below code be easily achieved with minimum coding.

``````\$ cluster1=(x y)
\$ cluster2=(a b)
\$ cluster3=(m)

\$ my=\$((\${cluster1+1}+\${cluster2+1}+\${cluster2+1}))

\$ echo \$my
3

\$ my=\$((\${cluster1+1}+\${cluster2+1}+\${cluster3+1}))
-bash: 1+1+: syntax error: operand expected (error token is "+")
``````
• You can't use the second element of an array of one. – Gerard H. Pille Sep 15 '18 at 6:03
• Yes, I was hoping if it can somehow return 0 or some other value , if element doesn't exist – Bharat Sep 15 '18 at 6:10
• What exactly do you want to do? – Mark Smith Sep 15 '18 at 6:31
• I wanted to count how many arrays has elements at first index, same way on second index with one liner code. – Bharat Sep 15 '18 at 6:39

## 2 Answers

Your code is generating a syntax error for each element that is not set.

``````\$ echo "\${cluster1+1}+\${cluster2+1}+\${cluster2+1}"
1+1+1

\$ echo "\${cluster1+1}+\${cluster2+1}+\${cluster3+1}"
1+1+
``````

It would be better to count the set elements instead of trying to calculate with a generated expression in this case:

``````#!/bin/bash

cluster1=(x y)
cluster2=(a b)
cluster3=(m)

for (( i = 0; i < 3; ++i )); do
is_set=( \${cluster1[i]+"1"} \${cluster2[i]+"1"} \${cluster3[i]+"1"} )
printf 'i=%d:\t%d\n' "\$i" "\${#is_set[@]}"
done
``````

This creates a new array, `is_set`, that will contain a `1` for each array that contains an element at index `i`. The `1` is unimportant and could be any string. The number of elements in the `is_set` array (`\${#is_set[@]}`) is then the number of set elements from the `cluster` arrays at that index.

Testing:

``````\$ bash script.sh
i=0:    3
i=1:    2
i=2:    0
``````
• nice... my=(\${cluster1+1} \${cluster2+1} \${cluster3+1}) ; echo \${#my[@]} – Bharat Sep 15 '18 at 8:42

May be a dirty trick, but how about prefixing a `0` (safe as the "Alternate Value" is a valid octal number):

``````my=\$((0\${cluster1+1}+0\${cluster2+1}+0\${cluster3+1}))
echo \$my
2
``````
• it's also nice.. – Bharat Sep 15 '18 at 8:45