Array, as in any programming language, is a collection of elements. These elements need not be of the same type. One important difference here is shells support only one-dimensional arrays.
1. Creating an array:
Creating an array is pretty simple.
$ typeset -a arr $ arr[0]=25 $ arr[1]=18 $ arr[2]="hello"Using the typeset command, we let the shell know that we are intending to use the variable arr to store a list of elements. The -a indicates arr as an indexed array. Then the elements are assigned one by one using their index positions. Array indexing always starts from 0.
To print the 1st element of the array:
$ echo ${arr[0]} 25Similarly, to print the 2nd element of the array:
$ echo ${arr[1]} 18To get the total number of elements in the array:
$ echo ${#arr[*]} 3To print all the elements of the array:
$ echo ${arr[*]} 25 18 helloOR
$ echo ${arr[@]} 25 18 hello
The difference between using the * and @ is same as the difference between using $* and $@ in case of command line arguments.
Declaring an initializing an array at one go:
$ typeset -a arr=(25 18 "hello")OR
$ typeset -a arr $ arr=(25 18 "hello")Array is initialized by having values inside brackets. Every element within the brackets are assigned to individual index positions.
Accessing the array elements one by one using a for loop:
for i in ${arr[*]} do echo $i doneSimilarly, we can access the array elements using for loop by using @ instead of *:
for i in "${arr[@]}" do echo $i donePrinting array elements using the printf :
$ printf "%s\n" ${arr[*]} 25 18 helloUsing array to store contents of a file
Let us create a file as shown below:
$ cat file Linux Solaris UnixDumping the file contents to an array:
$ arr=($(cat file))With this, every line of the file gets stored in every index position of the array. Meaning, the 1st line of the file will be in arr[0], 2nd line in arr[1] and so on.
$ echo ${arr[0]} LinuxSimilarly, to print the entire file contents:
$ echo ${arr[*]} Linux Solaris UnixGetting the total element count of the array in this case gives the line count of the file:
$ echo ${#arr[*]} 3
No comments:
Post a Comment