在Shell脚本中,我如何遍历包含其他变量的变量

时间:2016-10-13 05:59:29

标签: shell loops

我需要创建一个循环。循环变量包含其他变量。这就是我试过的

parentClients="name1 name2"
effectedClients="value1 value2"
otherClients="something1 something2 something3"
client_types="$parentClients $effectedClients $otherClients"
do
   echo $client
#this should print "parentClients" in 1st iteration and "effectedClients" in second and so on.
   for ct in $client
      do
        echo $ct
#this should print name1 name2 nd so on.
      done
      echo "done with one set"
done

此代码的问题在于它解析所有值并分配给变量client_types

1 个答案:

答案 0 :(得分:1)

使用bash

使用bash,我们可以使用数组和间接:

parentClients=(name1 name2)
effectedClients=(value1 value2)
otherClients=(something1 something2 something3)
client_types=(parentClients effectedClients otherClients)
for client in "${client_types[@]}"
do
   echo "client=$client"
   c=$client[@]
   for ct in "${!c}"
   do
      echo "  ct=$ct"
   done
   echo "done with one set"
done

这会产生输出:

client=parentClients
  ct=name1
  ct=name2
done with one set
client=effectedClients
  ct=value1
  ct=value2
done with one set
client=otherClients
  ct=something1
  ct=something2
  ct=something3
done with one set

语句parentClients=(name1 name2)创建一个名为parentClients的数组,其值为name1name2。表达式${!c}使用间接访问名称由c

指定的数组

使用POSIX shell

使用POSIX shell,我们必须使用变量而不是数组,而不是间接,我们使用eval

parentClients="name1 name2"
effectedClients="value1 value2"
otherClients="something1 something2 something3"
client_types="parentClients effectedClients otherClients"
for client in $client_types
do
   echo "client=$client"
   eval "client_list=\$$client" # Potentially dangerous step
   for ct in $client_list
   do
      echo "  ct=$ct"
   done
   echo "done with one set"
done

由于eval需要对数据来源​​有一定的信任,因此应谨慎使用。

这会产生输出:

client=parentClients
  ct=name1
  ct=name2
done with one set
client=effectedClients
  ct=value1
  ct=value2
done with one set
client=otherClients
  ct=something1
  ct=something2
  ct=something3
done with one set
相关问题