通过for循环动态更改unix中的变量名称

时间:2016-02-07 17:16:24

标签: unix for-loop dynamic-variables

Today=$(date)
for i in {2..15}
do
 week_{$i}=$(date -d "$Today +$i week")
 echo ${week_2}
done

我在BASH的输出中没有得到任何值。

1 个答案:

答案 0 :(得分:1)

一种方式......
    

    Today=$(date)
    for i in {2..15} 
    do
        tmp=$(date -d "$Today +$i week")
        eval week_${i}=\$tmp
        eval echo  \$week_${i}
    done
    

第二种方式......
    

    Today=$(date)
    for i in {2..15} 
    do
        week_[$i]=$(date -d "$Today +$i week")
        echo ${week_[$i]}
    done
第三种方式......

    Today=$(date)
    for i in {2..15} 
    do
        eval echo \${week_${i}:=$(date -d "$Today +$i week")} > /dev/null
    done

    for i in {2..15} 
    do
        eval echo  \$week_${i}
    done