Linux – Bash – Arrays

Background

Wanted to provide a quick sample code on using Arrays via Bash on a Linux System

Outline

  1. Declare Array
    • To create an empty array please use ()
      • Syntax
        • variable=()
      •  Sample
        • _register=()
  2. Add new entry to array
    • Syntax
      • array+=(variable)
    •  Sample
      • _register+=($1)
  3. Get Number of elements in array
    • Syntax
      • variable=${#array[@]}
    •  Sample
      • _numberofElements=${#_register[@]}
  4. Reference Array Element
    • Syntax
      • variable=${array[id]}
      • 0 based element id
    •  Sample
      • _number=${_register[$i]}

 

Code


#!/bin/bash

#declare array
_register=()

#add item to array
function bagit() {

    #Append new item
    _register+=($1)

}

#list all array elements
function listNumbers() {

    local _iNumberofElements=${#_register[@]}

    local i=0
    local iOffset=0

    while [ $i -lt $_iNumberofElements ]
    do

        _iOffset=$((i+1))

        _numbers=$((${_register[$i]}))

        echo "$_iOffset) $_numbers"

        i=$[$i+1]

    done

}

#total up array elements
function totalIT() {

    local _iNumberofElements=${#_register[@]}

    local i="0"

    local _total=0

    while [ $i -lt $_iNumberofElements ]
    do

        _total=$(( $_total + ${_register[$i]}))

        i=$[$i+1]

    done

    echo $_total

}

_iNumberofElements=0

#Add the follow elements
bagit 1

bagit 2

bagit 3

bagit 4

bagit 15

bagit 25

#Get number of elements
_iNumberofElements=${#_register[@]}

echo "Number of Elements $_iNumberofElements"

echo "All Elements at same time ${_register[@]}"

#invoke list elements
listNumbers

#add up  all numbers
_summed="$(totalIT)"

echo ""
echo ""
echo "Numbers summed is $_summed"

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s