read command help in bash
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:
- Read command reads from stdin. But in the above case how is it reading? echo puts the values on stdout.
- 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 e开发者_如何学JAVAlements in stdin, but i wanted stdout.
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.
A pipe ("|
") connects the preceding command's stdout to the following command's stdin.
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.
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?
精彩评论