1

I wanted to read output of a command in an array:

Something like:

(reformatted for code using {} above the input box)

var=`echo tell told till`
echo "$var" | while read temp; do echo $temp ; done  

This program will output:

tell 
told 
till

I had two questions:

  1. Read command reads from stdin. But in the above case how is it reading? echo puts the values on stdout.
  2. I wanted to know how to put those elements in an array? Basically how to put elements in stdout in an array. Read -a command can put the elements in stdin, but i wanted stdout.

4 Answers 4

2

If you want to put elements from stdout into array, eg

declare -a array
array=( $(my command that generates stdout) ) #eg array=( $(ls))

If you have a variable and want to put into array

$> var="tell till told"
$> read -a array <<< $var
$> echo ${array[1]}
till
$> echo ${array[0]}
tell

OR just

array=($var)

From bash reference:

   Here Strings
       A variant of here documents, the format is:

              <<<word

       The word is expanded and supplied to the command on its standard input.
Sign up to request clarification or add additional context in comments.

1 Comment

Tanks a ton for the soltion. It works!. Could you please tell me what is <<< symbol? I know about redirection, but its not the same. Kindly explain.
1

A pipe ("|") connects the preceding command's stdout to the following command's stdin.

1 Comment

Then why does'nt echo "$var" | read -a temp , store the values tell,told,till in temp array?
1

To split a string into words you can simply use:

for word in $string;
do 
    echo $word;
done;

So to do what you're asking

while read line
do
    for word in $line
    do
        echo $word
    done
done

And as Ignacio Vazquez-Abrams said, a pipe connects the left side's stdout to the right side's stdin.

Comments

0

When you use a pipe:

command1 | command2

The output of command1, written to the stdout, will be the input for command2 (stdin). The pipe "transforms" stdout to stdin.

And for the array: You give values to the array whith:

array=(val1 val2 val3)

So just try it:

array=($var)

You've got now $var in $array:

> echo ${array[*]}
tell
told
till

> echo ${array[1]}
told

Is this what you mean?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.