How can I sum all positive integers in a bash array.
Here is my code:
#!/bin/bash
arr=(2 43 -1 -33 24 12 -6)
for (( i = 0; i < ${#arr[@]}; ++i )); do
if (( arr[i] > 0 )); then
sum=`expr $sum + $i`
fi
done
echo "$sum"
First, you need to select the positive numbers, rather than the negative ones
if (( arr[i] > 0 )); then
then you need to sum the array values rather than the indices
sum=`expr $sum + ${arr[i]}`
or (since you are already using the (( ... )) arithmetic evaluation syntax elsewhere)
sum=$((sum + arr[i]))
(( sum += arr[i] ))
sum=0 for i in "${arr[@]}" do if (( "i" -gt 0 )); then sum =$psum+"$i" elif (( "i" -lt 0 )); then sum$nsum+"$i" fi done echo "positive = $psum" echo "negative = $nsum"
You could use a trick to replace all array elements starting (#) with a - with nothing.
This way you can skip the check in the loop.
$ arr=( 2 43 -1 -33 24 12 -6 )
$ echo "${arr[@]/#-*}"
2 43 24 12
And the modified script:
#!/bin/bash
arr=( 2 43 -1 -33 24 12 -6 )
sum=0
for i in "${arr[@]/#-*}"; do
(( sum+=i ))
done
echo "$sum"
This is my new attempt:
# 2+43+24+12=81
sum=0
arr=( 2 43 -1 -33 24 12 -6 )
arr=("${arr[@]/-*/0}")
sum=$(IFS=+; echo "$(( ${arr[*]} ))" )
echo "$sum"
81
echo $(( $(printf "%s+" ${arr[@]/#-*/0})"0" ))
Just for fun, you can also use awk to do the looping for you
arr=(2 43 -1 -33 24 12 -6);
sum=$(echo ${arr[*]} | awk '
BEGIN{RS=" "}
$0>0{sum+=$0}
END{print sum}');
echo $sum
81
Handy if you want to do something more than integer math
arr=(2 43 -1 -33 24 12 -6);
sqrt=$(echo ${arr[*]} | awk '
BEGIN{RS=" "}
$0>0{sum+=$0}
END{printf "%.2f", sum^0.5}');
echo $sqrt
9.00