-   Linux - General (
-   -   Store multi-line output into an array in a Linux bash script (

steven.c.banks 02-23-2009 12:32 PM

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 01: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:


find .

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

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

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

catkin 02-23-2009 02:35 PM

Hello Steven :)

#! /bin/bash

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



steven.c.banks 02-23-2009 05: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 12:29 PM

How about storing user input into an array?

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 03:08 PM

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

All times are GMT -5. The time now is 08:43 PM.