LinuxQuestions.org
Help answer threads with 0 replies.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 05-20-2009, 11:20 AM   #1
thewebbie
LQ Newbie
 
Registered: May 2009
Posts: 1

Rep: Reputation: 0
Getting SUM in Bash


Hi All;

Is it possible in bash to get the sum of numbers in a array?

for example I have an array with a series of numbers. I want the total.

array="1 2 3 4 5 6"
 
Old 05-20-2009, 11:42 AM   #2
colucix
LQ Guru
 
Registered: Sep 2003
Location: Bologna
Distribution: CentOS 6.5 OpenSuSE 12.3
Posts: 10,509

Rep: Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983
Look at the following script:
Code:
#!/bin/bash
#
#  Create the array
#
declare -a array
for i in {1..6}
do
  array[$i]=${i}
done
#
#  Sum array's elements
#
sum=0
for i in {1..6}
do
  sum=$(($sum + ${array[$i]}))
done
echo $sum
If you have floating point numbers, take in mind that bash can't manage them, so that you have to use bc or awk. Here is an example using bc:
Code:
#!/bin/bash
#
#  Create the array
#
declare -a array
for i in {1..6}
do
  array[$i]=${i}.2
done
#
#  Sum array's elements
#
sum=0
for i in {1..6}
do
  sum=$(echo "$sum + ${array[$i]}" | bc)
done
echo $sum
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
How to check the MD5 sum Gins Linux - General 12 05-21-2006 11:32 AM
md5 sum incorrect barrythai Fedora 3 10-10-2005 11:59 AM
knoppix and Md5 sum ??? bigjohn Linux - Newbie 10 09-27-2003 11:16 AM
MySQL SUM Query zimba Programming 3 03-28-2003 09:55 AM
Check sum emmanuelmathew Linux - Newbie 2 02-12-2003 01:14 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 02:05 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration