Get startedGet started for free

Summing an array

A common programming task is obtaining the sum of an array of numbers. Let's create a function to assist with this common task.

Create a Bash function that will take in an array of numbers and return its sum. We will use bc rather than expr to ensure we can handle decimals.

Your company's security rules state that all variables in functions must be restricted local scope so you will need to keep this in mind.

An array of numbers you can use for a test of your function would be the daily sales in your organization this week (in thousands):

14 12 23.5 16 19.34 which should sum to 84.84

This exercise is part of the course

Introduction to Bash Scripting

View Course

Hands-on interactive exercise

Turn theory into action with one of our interactive exercises

Start Exercise