开发者

explain the stages of this script

开发者 https://www.devze.com 2023-02-28 13:59 出处:网络
Can anyone please explain this shel开发者_StackOverflow社区l script? #!/bin/bash read a STR=\" $a\"

Can anyone please explain this shel开发者_StackOverflow社区l script?

    #!/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[*]}

Thank you.


Commented to exaplain every line.

#!/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)


The formatting has got really messed up in your post. Here's the re-formatted script:

#!/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[*]}

What it does it to turn around a list of words.

$ 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

and to describe how it works it first finds casts the string to an array, then it works out the number of items in the array, iterates through the array backwards by decrementing I and then echos out the resultant array

0

精彩评论

暂无评论...
验证码 换一张
取 消