Friday, February 6, 2009

arrays in bash shell

BASH shell is very powerful script language. In my previous blog posts, I give some detail about bash regular expression support. In this post, I will give some information about bash array support.
Declaring an array is very simple in bash. Here is some examples.

# declared an array named called "array" and containing elements.
# "This", "is", "an", "array"
array=(This is an array)

# declaring an array called a by giving elements one by one.
a[0]="123"
a[1]="abc"
a[2]="xyz"

# get output of an df -h

myarray=($(df -h))

Reading value element of an array is in following syntax ${array[#index_number]}. Please note the curly bracket notation.

# print element number 2 of array called myarray
echo ${myarray[2]}

# print all elements
echo ${myarray[*]}

# print index numbers of array
echo ${!myarray[*]}

# number of elements in array
echo ${#myarray[*]}

Here is a simple script using arrays. It simply reports the file systems where disk usage is
over 90% percent.

#!/bin/bash

(df -h|grep "^/") | while read d; do
array=( $d )
array[4]=${array[4]%\%}
if [ ${array[4]} -gt 90 ]; then
echo "${array[5]} is over limit. current size is ${array[4]}%"
#do whatever you want here, for example send an email to warn sysadmin about high disk usage.
fi
done

No comments: