我想要做的是循环的环境variables。 我有一些更改的安装,每个安装有3个IP来推送文件和运行脚本,我想尽可能自动化(所以我只需要修改一个文件,我将与源环境variables)。 以下是一个简单的版本,一旦我找出我可以解决我的问题。
所以在my.props中给出:
COUNT=2 A_0=foo B_0=bar A_1=fizz B_1=buzz
我想在下面的脚本中填写for循环
#!/bin/bash . <path>/my.props for ((i=0; i < COUNT; i++)) do <script here> done
这样我就可以从环境variables中获取值。 像以下(但实际工作):
echo $A_$i $B_$i
要么
A=A_$i B=B_$i echo $A $B
返回foo吧,然后发出嗡嗡声
$ num=0 $ declare A_$num=42 # create A_0 and set it to 42 $ echo $A_0 42 $ b=A_$num # create a variable with the contents "A_0" $ echo ${!b} # indirection 42
您可以迭代num并使用declare来创buildvariables和间接引用它们。 但是,你真的不喜欢使用数组吗?
for i in foo bar baz do some_array+=($i) # concatenate values onto the array done
要么
string="foo bar baz" some_array=($string)
这个怎么样?
$ cat IPs 192.168.0.1 192.168.0.2 192.168.0.3 $ cat readips #!/bin/bash while read -r ip do IP[count++]=ip # is it necessary to save them in an array, do_something_directly_with ip # if you use them right away? done < IPs
A=`eval echo \$A_$i`
在“高级Bash脚本指南”的“间接参考”一章中find答案
我需要这样做
eval A=\$A_$i eval B=\$B_$i
不知道我完全按照你的问题,但如果你想variables可用于儿童脚本使用内置的export :
kbrandt@kbrandt:~/scrap$ help export export: export [-nf] [name[=value] ...] or export -p NAMEs are marked for automatic export to the environment of subsequently executed commands.
从我认为你可能要做的事情来看,我只是把IP放在一个文件中,每行一个IP。 然后让安装脚本读取ip作为命令行参数:
while read ip; do ./install-script "$ip" done < file_with_ips
如果每条logging有多条数据,则可以删除它们:
kbrandt@kbrandt:~/scrap$ cat file_with_data 192.168.2.5:foobar:baz kbrandt@kbrandt:~/scrap$ while IFS=":" read -r ip data1 data2; do > echo "$ip@$data1@$data2" > done < file_with_data 192.168.2.5@foobar@baz