Handling arrays in bash scripts

You can create an array by using the following command: arrayname=( value1 value2 …. valueN ). Here we create an array with 5 elements.
myarray=( "string 1" "string 2" "string 3" "" "string4" ) or
myarray=( [0]="string 1" [1]="string 2" [2]="string 3" [4]="string 4" ) The quotes are necessary if you have spaces in the elements. Note that only initialized elements will be counted. E.g. this ( [1]=1 [3]=3 ) would only return 2 as the number of elements although we used 3 as the last index. The missing elements have a null value
To get a list of the ‘used‘ indices, use:
echo ${!myarray[*]}
To get the number of elements in an array, use:
echo ${#myarray[@]} or echo ${#myarray[*]}
To get a list of the elemets in an array, use:
echo ${myarray[@]}
To get a particular element of the array, use:
echo ${myarray[0]} Remember that the first value has index number 0. => returns the first element of the array
To get the length of a particular element, use:
echo ${#myarray[1]}=> returns the length of the second element of the array.
To un-initialise an element, use:
unset ${myarray[2]} => sets the value of the element with index 2(3rd element) to null.

Looping over an array

There are several ways to run over the content of an array. I prefer this ‘for loop‘, because it runs only over the initialized elements.

myarray=( [0]="string 1" [2]="string 2" [3]="string 3" [5]="" [6]="string4" )
 for index in ${!myarray[*]}
 do
    echo "${myarray[$index]}"
 done

About Juergen Caris

I am 54yo, MSc(Dist) and BSc in Computer Science, German and working as a Senior Server Engineer for the NHS Lothian. I am responsible for the patient management system, called TrakCare. I am a UNIX/Linux guy, working in this sector for more than 20 years now. I am also interested in robotics, microprocessors, system monitoring, Home automation and programming.
This entry was posted in Bash, Linux. Bookmark the permalink.

Leave a Reply

Your email address will not be published.