How to use Arrays in writing shell scripts

Basics
Note :
Arrays initialization described below will works only in bash shell.
sh will gives error as it can't interprit the arrays
use execute command as
bash

In Shell Scripting arrays are relatively easy to construct.
Example:
-----------------------------------------
#!/bin/bash
array=(red green blue yellow magenta)
len=${#array[*]}
echo "The array has $len members. They are:"
i=0
while [ $i -lt $len ]; do
echo "$i: ${array[$i]}"
let i++
done
------------------------------------------
Run this example:
$ ./myscript.sh
The array has 5 members. They are:
0: red
1: green
2: blue
3: yellow
4: magenta
Now, before you decide this is a silly, rather useless example, replace one line of the script and run it again:
array=(`ls`)
See what difference this makes (and think of all the kinds of lists you might create for this line).

Another example
------------------
#!/bin/bash
names=( Jaggu Teena Amma Sai )
for name in ${names[@]}
do
echo $name
# other stuff on $name
done
------------------
How to put a shell script in crontab to execute for every 5 minitues
0,5,10,15,20,25,30,35,40,45,50,55 * * * * bash /opt/kbabu/checklogs.sh > /opt/kbabu/errors_cron.log

Example to check logs using arrays
--------------------
#!/bin/bash
file=( "/opt/kbabu/log" "/opt/kbabu/log2" )
len=${#file[*]}
i=0;
while [ $i -lt $len ]
do
echo "file name : ${file[$i]}"
echo "checking log at time : `date`"
echo "`cat ${file[$i]} | grep Error`"
echo "`cat ${file[$i]} | grep ERROR`"
echo "`cat ${file[$i]} | grep Warning`"
echo "`cat ${file[$i]} | grep WARNING`"
i=`expr $i + 1`
done
--------------------


7 comments to "How to use Arrays in writing shell scripts"

Post a Comment

Who ever writes Inappropriate/Vulgar comments to context, generally want to be anonymous …So I hope U r not the one like that?
For lazy logs u can at least use Name/URL option which don’t even require any sign-in, good thing is that it can accept your lovely nick name also and URL is not mandatory too.
Thanks for your patience
~Krishna(I love "Transparency")
వీలయితే నాల్గు పోస్టులు ...కుదురితే ఒక కామెంటూ ...

Translate

Enter your email address:

Buffs ...

Visitors


hits counter
View My StatsCheck Google Page Rank

Add to Google Reader or Homepage

Bookmark and Share

Tags


Powered by WidgetsForFree

Archives