Wednesday, January 4, 2017

How to use arrays in ksh?



  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]}
25
Similarly, to print the 2nd element of the array:
$ echo ${arr[1]}
18
To get the total number of elements in the array:
$ echo ${#arr[*]} 
3
To print all the elements of the array:
$ echo ${arr[*]}
25 18 hello
  OR
$ 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
done
Similarly, we can access the array elements using for loop by using @ instead of *:
for i in "${arr[@]}"
do
    echo $i
done
Printing array elements using the printf :
$ printf "%s\n" ${arr[*]}
25
18
hello
Using array to store contents of a file
Let us create a file as shown below:
$ cat file
Linux
Solaris
Unix
Dumping 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]}
Linux
  Similarly, to print the entire file contents:
$ echo ${arr[*]}
Linux Solaris Unix
  Getting 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