LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Store multi-line output into an array in a Linux bash script (https://www.linuxquestions.org/questions/linux-general-1/store-multi-line-output-into-an-array-in-a-linux-bash-script-706878/)

steven.c.banks 02-23-2009 11:32 AM

Store multi-line output into an array in a Linux bash script
 
In a Linux bash script, how would I store each line of output from a command into individual elements in an array? Thanks in advance...

David the H. 02-23-2009 12:59 PM

My answer to your (fairly pointless, IMO ;)) poll is "could be better". I believe I understand basically what you want, but it needs more detail to make it really clear. What kind of "command" output are you talking about? Is it something simple like "find", or is it the output of a complex scripting function? Explaining exactly what you're trying to do is the most direct way to get help.

In any case, whether the input is space-separated or line-separated shouldn't matter generally, because the IFS defaults to both. I'm not an expert on arrays, but if, for example, you want to input the files in the current directory, you could do something like this:

Code:

find .
./afile.txt
./bfile.txt
./cfile.txt

testarray=( $(find .) )
echo ${testarry[@]}
./afile.txt ./bfile.txt ./cfile.txt

Another way could be to use a loop. Assuming $(command) gives your output:
Code:

N=0
for i in $(command) ; do
 
      testarray[$N]="$i"
      echo "$N = $i"    #to confirm the entry
     
  let "N= $N + 1"
done


catkin 02-23-2009 01:35 PM

Hello Steven :)
Code:

#! /bin/bash

i=1
ls | while read line
do
    array[ $i ]="$line"
    (( i++ ))
done

Best

Charles

steven.c.banks 02-23-2009 04:23 PM

Sorry - I was not sure what the poll was - please disregard. And thanks for the replies on my post - I incorporated in my script with no problems.

vbekker 12-05-2010 11:29 AM

How about storing user input into an array?
Code:

echo "Please enter some info (separated by spaces for example)
read var

how do i tell bash to store the values in var into an array? is there a way to set an IFS variable and automatically store into another array varriable or do i need to parse the variable and place the values into an array manually?
Thank YOu

catkin 12-05-2010 02:08 PM

vbekker, best start a new thread for your question :)


All times are GMT -5. The time now is 08:27 AM.