Bash – Arrays – Access Data Across Functions

Background

Learning Bash and here needing to modularize a bit, yet maintain access to data.

Array

It is a simple data structure, an Array

Pass By Reference

Code

#!/bin/bash

function dataGenerate()
{

  local id;
  local -n arrayDataLocal=$2
  local idMax=$1

  id=0

  while [ $id -lt $idMax ]; do

	arrayDataLocal[$id]=$[RANDOM]	  

        let id=id+1

  done  


   numberofArrayElements=${#arrayDataLocal[@]}
   

}

function dataDisplay()
{

   local id=0;
   
   local idMax=$1

   local -n arrayDataLocal=$2

   local numberofArrayElements=0

   numberofArrayElements=${#arrayDataLocal[@]}

   echo "Number of Array Elements $numberofArrayElements"

   while [ $id -lt $idMax ]; do

     dataEntry=${arrayDataLocal[$id]}

     echo "$id) $dataEntry"

     let id=id+1

   done	   

}


arrayData=()
idMax=10

dataGenerate $idMax arrayData

dataDisplay $idMax arrayData

Pass By Hierarchy

Code

#!/bin/bash

function dataGenerate()
{

  local id;
  local idMax=$1

  id=0

  while [ $id -lt $idMax ]; do

	arrayData[$id]=$[RANDOM]	  

        let id=id+1

  done  


   numberofArrayElements=${#arrayDataLocal[@]}
   

}

function dataDisplay()
{

   local id=0;
   
   local idMax=$1

   local numberofArrayElements=0

   numberofArrayElements=${#arrayData[@]}

   echo "Number of Array Elements $numberofArrayElements"

   while [ $id -lt $idMax ]; do

     dataEntry=${arrayData[$id]}

     echo "$id) $dataEntry"

     let id=id+1

   done	   

}


arrayData=()
idMax=12

dataGenerate $idMax 

dataDisplay $idMax 

 

 

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