Can the below code be easily achieved with minimum coding.

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

$ my=$((${cluster1[0]+1}+${cluster2[0]+1}+${cluster2[0]+1}))

$ echo $my

$ my=$((${cluster1[1]+1}+${cluster2[1]+1}+${cluster3[1]+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

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

$ echo "${cluster1[0]+1}+${cluster2[0]+1}+${cluster2[0]+1}"

$ echo "${cluster1[1]+1}+${cluster2[1]+1}+${cluster3[1]+1}"

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


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

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[@]}"

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.


$ bash script.sh
i=0:    3
i=1:    2
i=2:    0
  • nice... my=(${cluster1[1]+1} ${cluster2[1]+1} ${cluster3[1]+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):

echo $my
  • it's also nice.. – Bharat Sep 15 '18 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.