0

sh 版本:1.14.7

#!/bin/sh
cpu_to_eth1=10
cpu_to_eth2=20
cpu_to_eth3=30
cpu_to_eth4=40
i=0
for i in 1 2 3 4
do
 echo "value of the $i th varible is $cpu_to_eth$i"
done

它工作不正常,输出应该是

value of the 1 th varible is 10
value of the 2 th varible is 20
value of the 3 th varible is 30
value of the 4 th varible is 40
4

3 回答 3

1

使用bash,这里使用数组更合适,而不是多个变量。

数组示例:

cpu_to_eth_arr=( 10 20 30 40 )
for i in "${cpu_to_eth_arr[@]}"
do
    echo "$i"
done

另一种方式,使用关联数组:

cpu_to_eth[1]=10
cpu_to_eth[2]=20
cpu_to_eth[3]=30
cpu_to_eth[4]=40

for i in "${!cpu_to_eth[@]}"
do
    echo "value of the $i th varible is ${cpu_to_eth[$i]}"
done
于 2013-09-16T10:17:33.597 回答
1

无需bash

#!/bin/sh
cpu_to_eth1=10
cpu_to_eth2=20
cpu_to_eth3=30
cpu_to_eth4=40
for i in 1 2 3 4; do
  eval echo "value of the $i th varible is "$"cpu_to_eth$i"
done

这应该适用于任何 POSIX shell(例如dash,在 Ubuntu 中的默认 shell)。

关键是您需要两次评估(用于间接评估):

  1. 评估$i以获取变量的名称 ( cpu_to_eth$i)
  2. 评估变量cpu_to_eth$i以获得其实际值

二阶评估需要一个单独的eval(或 bash-ism)

于 2013-09-16T10:17:56.753 回答
0

使用bash您可以执行Shell 参数扩展

#!/bin/bash

cpu_to_eth1=10
cpu_to_eth2=20
cpu_to_eth3=30
cpu_to_eth4=40

i=0

for i in 1 2 3 4
do
 val=cpu_to_eth${i} # prepare the variable
 echo value of the $i th varible is ${!val} # expand it
done
于 2013-09-16T10:12:24.280 回答