首页 > 解决方案 > bash 脚本 shuf 并保存在列表中

问题描述

我有 A 数字,我想选择其中的 B 而不重复并保存到列表中。

像这样:

A="100"
B=5

a=$(gshuf -i 1-$B -n $A)
for i in ${a}
do
  echo $i
done

我该怎么做?

A 是我的代码中的一个字符串,我使用 gshuf 而不是 shuf 因为我在 Mac 中

标签: arraysstringbash

解决方案


您可以使用process substitution

A="100"
B=5

while read -r i; do
   echo "$i"
done < <(gshuf -i 1-$B -n $A)

如果要将生成的数字保存在数组中,请使用:

arr=()
while read -r i; do
   arr+=("$i")
done < <(gshuf -i 1-$B -n $A)

检查内容:

declare -p arr

推荐阅读