gpt4 book ai didi

Bash for循环设置一个变量,它的值,并评估它?

转载 作者:行者123 更新时间:2023-11-29 09:51:15 24 4
gpt4 key购买 nike

我如何使用 for 循环来定义一个变量,它的值,能够计算它?

我无法弄清楚评估部分,但使用 for 循环定义变量 它的值似乎有效。具体来说,

for i in {1..4}
do
export my${i}var="./path${i}_tofile"
# or
# export my${i}var=./path${i}_tofile
# or
# eval "my${i}var=\"./path${i}_tofile\""
echo $[my${i}var]
done

echo 没有正确求值,但 shell 确实正确地创建了变量和值。

echo $my1var

返回

./path1_tofile

但我需要使用 $i 作为变量名称的一部分来计算变量。

最佳答案

您应该改用数组变量:

declare -a myvar
for i in {1..4}
do
myvar[$i]="./path${i}_tofile"
done

更多详情:http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_10_02.html

关于Bash for循环设置一个变量,它的值,并评估它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42047532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com