2011-04-23 63 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