2013-04-24 140 views
2

我寫這樣一個腳本:讀取從命令輸出(輸出)的線到一個數組

#!/usr/bin/ksh93 

while read -A value; do 
    print -- "I am here" 
    print -- ${value[@]} 
done < `<command>` 

我的目的是重定向command的標準輸出輸出來填充所述陣列。以上用法受此鏈接啓發:http://www.unix.com/shell-programming-scripting/66884-array-ksh-elems-containing-spaces.html,但在我的情況下不起作用。

任何人都可以告訴我失敗的原因?

謝謝!

回答

3

使用的示例命令是ls -1 - 帶有shell/bin/ksh。這將該命令的輸出存儲在數組中。

ls -1 | { \ 
    n=0; 
    set -A array 
    while read line; do 
     array[$n]=$line 
     let n=$n+1 
    done; 
} 

# output commands here 
    for l in ${array[@]} 
    do 
     echo $l 
    done 
+1

謝謝。不過,我很困惑爲什麼我的代碼失敗了。它看起來很無辜。 – 2013-04-24 17:26:03

+0

非常有幫助。我也想更多地解釋爲什麼你的例子可行,爲什麼OP的代碼失敗。 – zarose 2014-09-18 19:12:14