Monday, December 5, 2011

Ways with Arrays

A collection of variables can be stored within one variable using an array.  It's fairly straghtforward; simply call like a variable like normal, but add a number after it with [] brackets, like this: variable[1]

This one's going to be a hefty example, so bear with me.

#!/bin/bash
#
#Array Demo
#By Jason Groce
#Created 12/5/2011
#
#An Array is a variable that contains multiple values.
#Each value is numbered after the name of the array,
#such as array[4], which may be used as a standard
#variable with special notation, such as $(array[12])
#

echo "This is a demo of how an Array functions."
echo -ne "You may pass a file name to populate the array "

echo "or enter variables manually."
echo -ne "(The file should contain names and numbers,"

echo "one of each per line.)"
echo

typeset -a names
typeset -a numbers
typeset -i num=0

if [ ! -f $1 ]||[ ! $# -eq 1 ]    #if no filename entered
then
        echo -ne "You did not enter a valid file name; "

        echo "begin manual entry."

        echo "Please enter 10 Names, one per line: "
        num=0
        while [ $num -lt 10 ]  #10 times, save name to record
        do
                read names[$num]
                num=$num+1
        done

        echo "Please enter 10 Numbers, one per line: "
        num=0
        while [ $num -lt 10 ]  #10 times, save number to record
        do
                read numbers[$num]
                num=$num+1
        done

else            #if a valid file name entered as parameter
        echo "You entered file $1"

        num=0
        echo "Populating arrays..."
        while read name number  #record name/number for each line
        do
                names[$num]=$name
                numbers[$num]=$number
                num=$num+1
        done < $1
fi

num=$num-1
typeset -i record=0
while [ ! $record -eq 99 ]
do
        echo -ne "Enter a number 0 to $num to display a record "

             "or '99' to quit: "
        read record
        case $record in
                99) echo "Quit"
                     exit
                     ;;
                *)  typeset -i recordNum=$record
                    echo -ne "Record $record "

                    echo -ne "${names[$recordNum]} "
                    echo "${numbers[$record]}"
        esac
done



This script can be coupled with a file containing names and numbers/values, such as this:

Paul pbille
Jason f52560
Richard f49150
Jonathan f51970


To try this out, creating the script as "arrays.sh" and the file as "arraydata.dat", run the command like this:

./arrays.sh arradata.dat

To summarize this, you create an array with typeset -a variable, add data to each array value like this, variable[5]="data", and access that data like this, ${variable[5]}.

Questions? Enjoy, weenix's!

No comments:

Post a Comment