Loading...
Shell Script

Array Variables

The variables in bash are scalar. From Bash 2.0 it supports Array variables i.e., it can handle multiple values at the same time. All the naming rules of Shell variables would be applicable for naming arrays. Shell doesn’t create a bunch of blank array items to fill the space between indexes. It keeps the track of an array index that contains values. In KSH numerical indicates for array must be between 0 and 1023 but in bash there is no limitation. The index supports only integer vales but not float and decimal values. If an array variable with the same name is defined as scalar variable then it becomes the value of the element of the array at index 0.

Syntax: Var[x]=value
Here, Var is the variable  name
x refers to the index value
value is the data that the array variable is holding.

Example:
employee[0]=”G Raj”
employee[1]=”K Rahul”

In the above example, employee is the variable name and  0,1 are the index value which are holding the data.
To use the array variable is same as variable i.e., to add $ before the variable name and also we have to add flower braces({}) while accessing the variable.

Access a variable
${name[x]}
To all the item in an array
${name[*]}   (or)   ${name[@]}
To get array size
${#name[@]}   (or)   ${#name[*]}

The below example narrates the usage of array variables.

#!/bin/bash
name[0]=Ram
name[1]=Rahul
name[2]=Raj
echo `echo ${name[0]} =`${name[0]}
echo `echo ${name[1]} =`${name[1]}
echo`echo ${name[2]} =`${name[2]}
echo`echo ${name[*]} =`${name[*]}
echo`echo ${name[@]} =`${name[@]}
echo`echo ${#name[*]} =`${name[*]}
echo`echo ${#name[@]} =`${name[@]}

OUTPUT:

$ ./array1.sh r
echo ${name[0]}=Ram
echo ${name[1]}=Rahul
echo ${name[2]}=Raj
echo ${name[*]}=Ram Rahul Raj
echo ${name[@]}=Ram Rahul Raj
echo ${#name[*]}=3
echo ${#name[@]}=3

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *