1827452 Members
4667 Online
109965 Solutions
New Discussion

Arrays in shell

 
SOLVED
Go to solution
dude70_1
Advisor

Arrays in shell

Guys,

I want to put some values in a array in my script and check them for a condition.
Ex.
***************
arr[0]=value1
arr[1]=value2
arr[2]=value3

var=value3

while(arr.length)
if ($var == arr[x])
then
do somthing
fi

***************

Can someone help me!

Thanks in advance.
5 REPLIES 5
A. Clay Stephenson
Acclaimed Contributor

Re: Arrays in shell

arr[0]=value1
arr[1]=value2
arr[2]=value3

var=value3
typeset -i10 I=0
while [[ ${I} -lt ${#arr[*]} ]]
do
if [[ "${arr[${I}]}" = "${var}" ]]
then
echo "Do something"
fi
(( I += 1 ))
done
If it ain't broke, I can fix that.
dude70_1
Advisor

Re: Arrays in shell

Hi Stephen,

Thanks for the reply. Can you explain few more things. How do I put the values in the array and what does "typeset -i10 I=0 " this line do. Is it min and max values of array?

Thanks

Michael Schulte zur Sur
Honored Contributor

Re: Arrays in shell

Hi dude70,

the typeset defines the variable l as 10 character integer and initializes it with zero. The index of a one dimensional array is limited to 1023. The assignment, you choose is ok. Where you get your data from, is up to you.

greetings,

Michael
dude70_1
Advisor

Re: Arrays in shell

Thanks Mike!
I am reading the values from a file.
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Arrays in shell

Actually typeset -i10 I=0 declares I to be a base 10 integer and assigns its initial value at zero.

To read the values into a file is also quite simple:

typeset -i10 KNT=0
INFILE="/var/tmp/myfile"

cat ${INFILE} | while read arr[${KNT}]
do
(( KNT += 1))
done

var="Two"
typeset -i10 I=0
while [[ ${I} -lt ${KNT} ]]
do
if [[ "${arr[${I}]}" = "${var}" ]]
then
echo "Do something"
fi
(( I += 1 ))
done

Assignments to array elements are just like assignments to a simple variable.
If it ain't broke, I can fix that.