本文介绍了在KornShell中构建动态变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个搜索,但没有找到任何类似于我想要做的事情。
我有一个服务器主机名和IPs




  • Servera | IPa

  • Serverb | IPb

  • Servern | IPn



我想要这个文件,并将每个元素放入变量




  • Server_Var_1

  • IP_Var_1

  • Server_Var_2

  • IP_Var_2

  • Server_Var_n

  • IP_Var_n



我目前拥有的是以下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

任何帮助都不胜感激。

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

counter = 0
而IFS =|读取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


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.

解决方案
$ 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

这篇关于在KornShell中构建动态变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-26 11:28