如何反转为定义的数组执行for循环的顺序
要迭代数组,我这样做:
$ export MYARRAY=("one" "two" "three" "four")
$ for i in ${MYARRAY[@]}; do echo $i;done
one
two
three
four
Run Code Online (Sandbox Code Playgroud)
有没有可以反转数组顺序的函数?
我有一个想法是生成一系列反向索引并使用这个反向索引调用元素,但也许有更快的替代方案,或者至少更容易阅读.
cho*_*oba 61
您可以使用C风格的循环:
for (( idx=${#MYARRAY[@]}-1 ; idx>=0 ; idx-- )) ; do
echo "${MYARRAY[idx]}"
done
Run Code Online (Sandbox Code Playgroud)
对于具有"孔"的数组,元素的数量${#arr[@]}与最后一个元素的索引不对应.您可以创建另一个索引数组并以相同的方式向后移动:
#! /bin/bash
arr[2]=a
arr[7]=b
echo ${#arr[@]} # only 2!!
indices=( ${!arr[@]} )
for ((i=${#indices[@]} - 1; i >= 0; i--)) ; do
echo "${arr[indices[i]]}"
done
Run Code Online (Sandbox Code Playgroud)
ber*_*eal 23
你可以使用tac,这与cat它反转线条的意义相反.
MYARRAY=("one" "two" "three" "four")
for item in "$MYARRAY"; do
echo "$item";
done | tac
# four
# three
# two
# one
Run Code Online (Sandbox Code Playgroud)
_arr+=( '"${_arrev} is an actual "${array[@]}"' ) ?
_arr+=( '"${_arrev} is created as a result"' )
_arr+=( '"of reversing the key order in"' )
_arr+=( '"this "${_arr}. It handles zsh and"' )
_arr+=( '"bash arrays intelligently by tracking"' )
_arr+=( '"shell "$ENV." quotes=fine ( i hope ) "' )
. <<REVERSE /dev/stdin ?
_arrev=( $(: $((l=${#_arr[@]}${ZSH_VERSION++1})) ; printf '"${_arr[$(('$l'-%d))]}" ' `seq 1 $l`) )
REVERSE
echo ; printf %s\\n ${_arrev}
"shell "$ENV." quotes=fine ( i hope ) "
"bash arrays intelligently by tracking"
"this "${_arr}. It handles zsh and"
"of reversing the key order in"
"${_arrev} is created as a result"
"${_arrev} is an actual "${array[@]}"
Run Code Online (Sandbox Code Playgroud)
我认为这应该处理任何可能的数组.
如果你对那里发生的事情感兴趣,我建议你先看看这里.也许在这里,肯定在这里,如果你有时间,这里和这里.
在所有这些答案中,我将讨论here-document (以及许多其他方面)的不同方面,您可以利用这些方面的优势.例如,我讨论了两次评估变量,这是在上面完成的,并在一个声明一个函数,全局声明另一个函数"_$1"只用5或6行命名- 其中大多数是_$1() { func body ; }.如果你正确使用它,它会非常方便.
关于bash/zsh, 井之间的自动切换,这是另一回事,但也非常简单.看到这里.