Building Dynamic Variable Names in KornShell

2019-08-09 22:27发布

问题:

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