LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Generating iteratable arrays in bash (https://www.linuxquestions.org/questions/programming-9/generating-iteratable-arrays-in-bash-353140/)

d00bid00b 08-14-2005 10:24 AM

Generating iteratable arrays in bash
 
I am wanting a command to populate an array with its output, for example:

slocate newfile > An_Array

Which would then allow a second command to iterate through An_Array, such as:
Code:

for x in An_Array
do
    rm -ir
done

This should pass the output of slocate to a list which then when iterated through will allow the user to opt to remove a specified file. At least, that's the theory!! :)

Any thoughts?

leonscape 08-14-2005 10:58 AM

So your looking for something like?

Code:

#!/bin/sh

until [ -z $1 ]; do
  An_Array[i++]=$1
  shift
done

for(( j = 0; j < i; ++j )); do
    echo "Element $j = ${An_Array[j]}"
done

This would produce:
Code:

$ ./test One two three
Element 0 = One
Element 1 = two
Element 2 = three


d00bid00b 08-14-2005 11:24 AM

Hmmm ... looks about right. Let me test it out and get back to you.

Thanx

d00bid00b 08-15-2005 12:25 PM

Thanks for the script leonscape. The mechanics seem okay, but now I need to figure out how to get the output of slocate to be loaded into An_Array. I tried slocate myfile_name > An_Array which gave me a text file of the output of slocate ... which was not what I had in mind.

How could I:
(a) accept input from a user (i.e. what file they want to slocate), and
(b) dynamically populate an array with the output of slocate so that it can be iterated over?

Thanks

leonscape 08-15-2005 04:54 PM

$1 works for command line inputs. So that is what the user could enter to the command. i think the easiest way of iterating the slocate return is to push it out to a temp file and read it into an array. Not being a Bash guru, i couldn't think of a way to redirect a command output to an array. So what I would end up with is:

Code:

#!/bin/sh

# The command name, So it doesn't matter if the script gets renamed.
CMD=`basename $0`

# the help screen, done like this so you can expand the explanation
# between cat and end.
help_screen ()
{
cat <<END
    Usage: $CMD files..."
END
exit
}

# check theres something to process
if [ $# -eq 0 ]; then
    help_screen
fi

echo > tmpfile #Truncate the file

# doesn't matter how many they request appends the lot
# to one file.
until [ -z $1 ]; do
  slocate $1 >> tmpfile
  shift
done

# Now reads that file into an array
An_Array=( $(cat tmpfile) )

#now prints out the whole file
for i in $(seq 0 $((${#An_Array[@]} - 1))); do
  echo "${An_Array[$i]}"
done



All times are GMT -5. The time now is 07:09 AM.