Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

using arrays in shell script 2

Status
Not open for further replies.

minus0

Programmer
Feb 20, 2003
73
US
How do you use arrays in a shell script (korn shell on a solaris box)? Let's say, I do a ls -l and there are four files, I would get back 5 lines as

total 12
-r--r----- 1 user root 917 Aug 10 2004 file1.log
-r--r----- 1 user root 917 Aug 10 2004 file2.log
-r--r----- 1 user root 917 Aug 10 2004 file3.log
-r--r----- 1 user root 917 Aug 10 2004 file4.log

I am trying to capture the names of the files in to an array (just to try out arrays) and then display the names of the files by doing an echo ${array[0]}..., but doing something horribly wrong. How do you do this?
 
A starting point:
set -A myArr=$(ls)
echo ${myArr[0]}

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
set -A array $(ls file*.log) #sets the array to "array"
print ${array[@]} #prints all files in the array
print ${#array[@]} #prints the total number in the array

Your problem is that you are doing an 'ls -l' which is setting everything (i.e., 1, user, root, 917). You can get around this if you want by setting a counter to increment your print by 9 each time to print only the file name.
 
Try this (from member kHz)

Code:
#!/bin/ksh

INDEX=0

set -A ARRAY $(ls -1 *.log)

while [[ -f ${ARRAY[$INDEX]} ]]
do
    print "Found: ${ARRAY[$INDEX]}"
    (( INDEX += 1 ))
done
Hope this helps.
 
Code:
#!/bin/ksh
set -A array $(ls -l /tmp/junk)
filecount=${#array[@]}
i=0
c=0
while (( i < filecount ))
do
        if [[ ${array[$i]} = file* ]]; then
                ((c+=1))
                print "I found a match at array element $i."
        fi
((i+=1))
done
exit 0
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top