Building Dynamic Variable Names in KornShell

穿精又带淫゛_ 提交于 2019-12-11 11:29:11

问题


I did a search but did not find anything quite like what I am trying to do. I have a list of Server Hostnames & IPs

  • Servera | IPa
  • Serverb | IPb
  • Servern | IPn

I want to cat this file and put each element into variables

  • Server_Var_1
  • IP_Var_1
  • Server_Var_2
  • IP_Var_2
  • Server_Var_n
  • IP_Var_n

What I currently have is the following KornShell (ksh):

Counter=0
cat hostfile|while read line; do
Server_Var_"$Counter"=echo $line | awk -F"|" '{print $1}'
IP_Var_"$Counter"=echo $line | awk -F"|" '{print $2}'
echo $Server_Var_[*] $IP_Var_[*]
done

Any help is appreciated.


回答1:


$ cat hostfile
server1 | 192.168.1.101
server2 | 192.168.1.102
server3 | 192.168.1.103
$ cat foo
#!/bin/sh

counter=0
while IFS=" |" read name ip; do
    eval Server_VAR_$counter=$name
    eval IP_VAR_$counter=$ip
    : $(( counter += 1 ))
done < hostfile

echo $Server_VAR_0:$IP_VAR_0
echo $Server_VAR_1:$IP_VAR_1
echo $Server_VAR_2:$IP_VAR_2
$ ./foo
server1:192.168.1.101
server2:192.168.1.102
server3:192.168.1.103



回答2:


Here's a slight twist to the original question (which was perfectly answered by @William Pursell). So this bit of code will produce the same output, but uses an array of compound variables instead. Note that this is specific to ksh93.

$ cat  read_hostvars

#!/bin/sh

counter=0
typeset -a Server
while IFS=" |" read name ip; do
    Server[counter].name=$name
    Server[counter].ip=$ip
    (( counter++ ))
done < hostfile

for n in ${!Server[@]}; do
    echo ${Server[n].name}:${Server[n].ip}
done


来源:https://stackoverflow.com/questions/12292122/building-dynamic-variable-names-in-kornshell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!