Shell Script Tutorial

Array

The use of array variable structures can be invaluable. This recipe describes several methods for delcaring arrays in bash scripts.

Example 1 - Array
This creates 3 array elements, each containing a space.

domain=( "a.com" "b.com" "c.com" )

for i in ${domain[@]} ; do
echo $i
done

Result:
a.com
b.com
c.com

Example 2 - MultiArray
Two array is combined into another array.

domain=( "a.com" "b.com" "c.com" )
domain2=( x "y.com" "z.com" )
mdomain=( "${domain[@]}" "${domain2[@]}" )

for i in ${mdomain[@]} ; do
echo $i
done

Result:
a.com
b.com
c.com
x.com
y.com
z.com

Example 3 - Array
This declares three elements of an array using nonsequential index values and creates a sparse array (there are no array elements for index values 1 or 2).

domain[0]="a.com"
domain[3]="b.com"
domain[4]="c.com"

for i in ${domain[@]} ; do
echo $i
done

Result:
a.com
b.com
c.com

Example 4 - Array for file content
This example places the contents of the file filename into an array. The tr command converts newlines to spaces so that multiline files will be handled properly.

array=( `cat tmp.txt | tr '\n' ' '` )

for i in ${array[@]} ; do
echo $i
done



Server is hosted by Alanstudio
Linux Operating System

Recommend screen resolution 1024 x 768 / IE / FireFox
Alan Studio © 2007 by Alan Cheung Hin Lun. All rights reserved.