View Full Version : BASH arrays
c0mput3r_n3rD
July 12th, 2009, 07:36 PM
Hello,
I'm writing a script that makes a link of all the files in the pwd, and puts the links in another directory. For this I want to put the values of the ls command into an array, and then I can step through the array using a for loop. Can any one help with storing the values of the ls command in an array?
thanks
MadCow108
July 12th, 2009, 08:10 PM
i=0
while read line;
do
files[i++]=$line;
done < <(ls)
for (( i = 0 ; i < ${#files[@]} ; i++ ))
do
echo ${files[$i]}
done
wouldn't it be easier to do it in one step for such a simple task?
c0mput3r_n3rD
July 12th, 2009, 08:19 PM
i=0
while read line;
do
files[i++]=$line;
done < <(ls)
That's asking for user input.
I'm looking for more of a :
myArray='ls'
type of thing
MadCow108
July 12th, 2009, 08:21 PM
yes it stores everything ls lists in an arry
for only files modifiy the ls command (e.g. ls -1 | grep -v ^d)
works on my machine
GNU bash, version 3.2.48(1)-release (i486-pc-linux-gnu)
c0mput3r_n3rD
July 12th, 2009, 08:24 PM
i=0
while read line;
do
files[i++]=$line;
done < <(ls)
will get everything ls lists, and then i can use the for loop to step through the array that was created?
MadCow108
July 12th, 2009, 08:29 PM
oh right:
IFS=$'\n'
files=(`ls -1`)
unset IFS
is a much easier solution :)
IFS change so it handles spaces correctly
c0mput3r_n3rD
July 12th, 2009, 08:47 PM
Awsome! Thank you very much :D
MadCow108
July 12th, 2009, 08:52 PM
the unset IFS may be problematic when you need it again
better:
bac=$IFS
IFS=$'\n'
files=(`ls -1`)
IFS=$bac
ghostdog74
July 13th, 2009, 02:03 AM
you don't need arrays for this
find /path -type f | while read FILE
do
#do your stuff with $FILE
done
kaibob
July 13th, 2009, 02:17 AM
I'm just learning arrays, but it was mentioned in another thread that you can create an array as in the following:
array=( * ) ; for f in "${array[@]}" ; do echo "$f" ; done
Is it necessary to use ls?
ghostdog74
July 13th, 2009, 02:31 AM
Is it necessary to use ls?
no need.
Powered by vBulletin® Version 4.2.2 Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.