2011-04-21 58 views
1

命令帮助我想在阵列中读取的命令的输出:读取在bash

是这样的:

(重新格式化用于使用{}上面的输入框代码)

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

这一计划将输出:

tell 
told 
till 

我有两个问题:

  1. 读取命令从标准输入读取。但在上述情况下,它如何阅读? echo将值放在stdout上。
  2. 我想知道如何将这些元素放入数组中?基本上如何将元素放入数组中的标准输出。阅读 - 一个命令可以把元素标准输入,但我想标准输出。

回答

2

如果你想要把元素从标准输出到数组,如

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

如果你有一个变量,要投入阵列

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

或只是

array=($var) 

从bash参考:

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

       <<<word 

     The word is expanded and supplied to the command on its standard input. 
+0

坦克一吨的soltion。有用!。你能告诉我什么是<<<符号吗?我知道重定向,但它不一样。请解释一下。 – Pkp 2011-04-21 05:50:08

1

管道(“|”)将上述命令的stdout连接到以下命令的stdin。

+0

那么为什么不回声“$ var”|读-a temp,存储值告诉,告诉,直到在临时阵列? – Pkp 2011-04-21 01:55:28

+0

这是一个完全不同的问题。 http://mywiki.wooledge.org/BashFAQ/024 – 2011-04-21 01:58:08

1

要分割字符串转换成的话,你可以简单地使用:

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

所以做你问

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

而作为伊格纳西奥巴斯克斯 - 艾布拉姆斯说,管左连接什么方的标准输出到右侧的标准输入。