我正在尝试遍历数组并动态选择一个随机元素来取消设置。我尝试了以下内容:
a=('red' 'green' 'black' 'yellow' 'white' 'orange' 'blue' 'purple')
while [ ${#a[@]} -ne 0 ]
do
echo "Length of array:" ${#a[@]}
randomnumber=$(( ( RANDOM % (${#a[@]}) ) ))
echo "random number "$randomnumber" -> "${a[$randomnumber]}
unset a[$randomnumber]
done
每个循环的长度似乎都是正确的,但是当我访问一个之前未设置索引的元素时,内容为空。我读了一些关于 subshell 的内容,但不知道这意味着什么。 unset 真的会重新排列数组吗?有人可以提示我如何解决这个问题吗?
最佳答案
如果取消设置元素 2,则元素 3 不是新元素 2。
# define your array as example
a=('red' 'green' 'black' 'yellow' 'white' 'orange' 'blue' 'purple')
# show array with index in declare's style
declare -p a
输出:
declare -a a='([0]="red" [1]="green" [2]="black" [3]="yellow" [4]="white" [5]="orange" [6]="blue" [7]="purple")'
# remove element 2 (black)
unset a[2]
declare -p a
输出(无元素2):
declare -a a='([0]="red" [1]="green" [3]="yellow" [4]="white" [5]="orange" [6]="blue" [7]="purple")'
A possible solution: copy array to rearrange index:
a=("${a[@]}")
declare -p a
输出:
declare -a a='([0]="red" [1]="green" [2]="yellow" [3]="white" [4]="orange" [5]="blue" [6]="purple")'
关于arrays - 从 Bash 数组中删除随机元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27981746/