2013-07-29 125 views
1

我想讀取命令輸出的第一行。但我得到一個空的消息。爲什麼「讀取」不會讀取命令輸出的第一行?

我用

ls | read line 
echo $line #nothing displayed 

爲什麼行變量是空的,如何解決?

以下代碼有效。但我想只讀第一行

ls | while read line; do 
    echo $line 
done 

如果這是不可能的讀取,是有可能與如grep等功能做到這一點時,awk,sed的?

+5

不要分析'ls'。使用'in line in *;做'迭代文件。 – chepner

回答

4

read確實讀取了第一行,但它正在子shell中執行。但你可以這麼做:

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

您可以使用

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

但前面已經提到,請,請,請不解析ls輸出!