在 bash 中创建具有动态索引的变量

Create variables with dynamic index in bash

我的代码应该适用于#!/bin/sh
有没有一种方法可以在循环中用迭代次数声明一个变量?
代码:

n=0
somestring="asdf asdf"
while [ $n -le 10 ]
do
    "var$n"="$somestring"
done

# now it is possible to call variables var0, var1, var2,...
>> echo $var2
asdf asdf   

感谢您的回答!

您可以使用 export :

while [ $n -le 10 ]
do
    export "var$n=$somestring"
    n=$((n+1))
done

eval

while [ $n -le 10 ]
do
    eval "var$n=\"$somestring\""
    n=$((n+1))
done