我想阅读命令输出的第一行。但我收到一条空信息。
我用过
ls | read line
echo $line #nothing displayed
为什么line变量为空以及如何解决?
以下代码有效。但我想只阅读第一行
ls | while read line; do
echo $line
done
如果无法读取,是否可以使用其他功能,如grep,awk,sed?
答案 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
输出!