read 管道 子shell 無法賦值問題的解決

from: http://truenight0.com/read_from_pipes.html


問題

最近有一個需求,需要把一個命令的結果分別寫入幾個變量中,於是想到了用read:

 
echo a b c | read x y z

可是問題來了,打印出x,y,z均顯示爲空

 
echo $x $y $z  #結果爲空

原來在管道的右邊會打開一個子進程,所以讀到的變量都是子進程中的,父進程中無法顯示

解決方法

1. 使用here string

 
read x y z <<< $(echo a b c)

2. 先把第一個命令的結果重定向到文件,再從文件中讀取

 
echo a b c > file
read x y z < file

解另一個例子

 
cat file | while read line
do
    var=${line}
done
echo ${var}   # 結果爲空

while read line
do
    var=${line}
done < file
echo ${var}  # 正確顯示

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章