【发布时间】:2011-08-11 16:17:54
【问题描述】:
谁能解释一下这个shell脚本?
#!/bin/bash 读一个 STR="$a" ARR=($STR) LEN=${#ARR[*]} 最后=$(($LEN-1)) ARR2=() 我=$LAST 而 [[ $I -ge 0 ]];做 ARR2[${#ARR2[*]}]=${ARR[$I]} 我=$(($I-1)) 完毕 回声 ${ARR2[*]}谢谢。
【问题讨论】:
谁能解释一下这个shell脚本?
#!/bin/bash 读一个 STR="$a" ARR=($STR) LEN=${#ARR[*]} 最后=$(($LEN-1)) ARR2=() 我=$LAST 而 [[ $I -ge 0 ]];做 ARR2[${#ARR2[*]}]=${ARR[$I]} 我=$(($I-1)) 完毕 回声 ${ARR2[*]}谢谢。
【问题讨论】:
评论解释每一行。
#!/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)
【讨论】:
您的帖子中的格式确实搞砸了。这是重新格式化的脚本:
#!/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 向后迭代数组,然后回显出结果数组
【讨论】: