为什么"阅读"不读取命令输出的第一行?

时间:2013-07-29 13:52:08

标签: linux bash shell sh busybox

我想阅读命令输出的第一行。但我收到一条空信息。

我用过

ls | read line
echo $line #nothing displayed

为什么line变量为空以及如何解决?

以下代码有效。但我想只阅读第一行

ls | while read line; do 
    echo $line
done

如果无法读取,是否可以使用其他功能,如grep,awk,sed?

2 个答案:

答案 0 :(得分:4)

read确实读取了第一行,但它正在子shell中执行。但你可以这样做:

ls | { read line; 
  echo $line;
  # other commands using $line;
}
# After the braces, $line is whatever it was before the braces.

答案 1 :(得分:2)

您可以使用

read line <<< "$(ls)"
printf "%s\n" "$line"

但正如已经提到的那样,请,不要解析ls输出!