2011-04-23 67 views
0

任何人都可以請解釋這個shell腳本嗎?解釋這個腳本的階段

 
    #!/bin/bash 
    read a 
    STR=" $a " 
    ARR=($STR) 
    LEN=${#ARR[*]} 
    LAST=$(($LEN-1)) 

    ARR2=() 
    I=$LAST 
    while [[ $I -ge 0 ]]; do 
     ARR2[ ${#ARR2[*]} ]=${ARR[$I]} 
     I=$(($I-1)) 
    done 

    echo ${ARR2[*]} 

謝謝。

回答

2

評論exexlain每一行。

#!/bin/bash 
read a # Reads from stdin 
STR=" $a " # concat the input with 1 space after and three before 
ARR=($STR) # convert to array? 
LEN=${#ARR[*]} # get the length of the array 
LAST=$(($LEN-1)) # get the index of the last element of the array 

ARR2=() # new array 
I=$LAST # set var to make the first, the last 

while [[ $I -ge 0 ]]; do # reverse iteration 
    ARR2[ ${#ARR2[*]} ]=${ARR[$I]} #add the array item into new array 
    I=$(($I-1)) # decrement variable 
done 

echo ${ARR2[*]} # echo the new array (reverse of the first) 
1

格式在你的文章中真的搞砸了。這裏是重新格式化的腳本:

#!/bin/bash 

read a 
STR=" $a " 
ARR=($STR) 
LEN=${#ARR[*]} 
LAST=$(($LEN-1)) 

ARR2=() 
I=$LAST 
while [[ $I -ge 0 ]]; 
    do ARR2[ ${#ARR2[*]} ]=${ARR[$I]} 
    I=$(($I-1)) 
done 

echo ${ARR2[*]} 

它是如何扭轉單詞列表。

$ echo "a b c d e f" | ./foo.sh 
f e d c b a 

$ echo "The quick brown fox jumps over the lazy dog" | ./foo.sh 
dog lazy the over jumps fox brown quick The 

,並描述它的工作原理它首先找到連鑄字符串數組,然後它的作品了通過陣列數組中的項,迭代的數量向後通過遞減I然後回聲出所得陣列

+0

我希望我沒有爲你做功課! – 2011-04-24 00:01:25