任何人都可以解释一下这个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[*]}
谢谢。
答案 0 :(得分:2)
评论开头每一行。
#!/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 :(得分: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
向后遍历数组,然后回显结果数组