Wednesday, August 17, 2016

Bash-sum of each array-Debug on

#!/usr/bin/env bash
#This script is very simple example that sum each array numbers.
#debug on
set -x
var="15899"
echo "first is ${var:0:1}"
echo "second is ${var:1:1}"
echo "third is ${var:2:1}"
echo "fourth is ${var:3:1}"
echo "fifth is ${var:4:1}"

sum=0
start=0
while (( $start < ${#var} ))
do
   sum=$(( $sum+${var:start++:1} ))
done
echo -e "Total sum is \e[;35m $sum \e[;0m"



#Just testing for fun.
young@ubuntu-16:~$ bash sum.sh
+ var=15899
+ echo 'first is 1'
first is 1
+ echo 'second is 5'
second is 5
+ echo 'third is 8'
third is 8
+ echo 'fourth is 9'
fourth is 9
+ echo 'fifth is 9'
fifth is 9
+ sum=0
+ start=0
+ ((  0 < 5  ))
+ sum=1
+ ((  1 < 5  ))
+ sum=6
+ ((  2 < 5  ))
+ sum=14
+ ((  3 < 5  ))
+ sum=23
+ ((  4 < 5  ))
+ sum=32
+ ((  5 < 5  ))
+ echo -e 'Total sum is  \e[;35m 32 \e[;0m'
Total sum is   32
young@ubuntu-16:~$

No comments:

Post a Comment