简体   繁体   English

我如何在bash循环中从文件分配这些配置变量

[英]how do i assign these config variables from file in a bash loop

i have a configuration file with definitions like: 我有一个配置文件,其定义如下:

[BEGIN 1]
age=16
sex=M
height=1.5
weight=20
[END 1]
...
[BEGIN 4]
age=17
sex=F
height=1.3
weight=40
[END 4]

I need to loop through these like so in another script: 我需要像在另一个脚本中那样遍历这些:

worker_exec  $age  $sex  $height $weight -update | tee output.log

I was thinking if i only had one occurence in the config file i would remove the [BEGIN.. and [END.. lines and source it. 我在想如果我在配置文件中只出现一次,我会删除[BEGIN ..和[END ..]行并将其来源。 But now there are multiple definitions, how would i read this file and get those definitions in bash variables and use them? 但是现在有多个定义,我将如何读取该文件并在bash变量中获取这些定义并使用它们? I also thought to use temporary files, then it occured to me that extracting the N^(th) section is something i dont know how to do with awk 我还认为要使用临时文件,然后我想到提取N ^(th)节是我不知道如何使用awk的事情

End result is i can run 最终结果是我可以跑步

for item in ...# something here i dont get, maybe also unset any previous
               # definitions in previous loop if neccessary.
do
 worker_exec  $age  $sex  $height $weight -update | tee output.log
done

If i understand what you want this should work. 如果我明白你想要什么,这应该工作。

Awk to format it Sets FS(Field Separator) to = Awk将其格式化将FS(Field Separator)设置为=
Sets ORS(Output Record Separator) to nothing 设置ORS(输出记录分隔符)为空

If it has [END on line print new line If it does have [END or [BEGIN print line with a space(notice as ORS is nothing this does not print a new line) 如果它有[END在行上打印新行,如果它有[END[BEGIN在行上打印空格(请注意,因为ORS为空,所以不会打印新行)

Then just read through the lines as they are in the correct order the full line can be passed to worker_exec as it will be resolved prior 然后只需按正确的顺序阅读各行,就可以将整行传递给worker_exec,因为它将在

Triple redirect is used to pass variable into a loop. 三重重定向用于将变量传递到循环中。

VARS=$(awk 'BEGIN {FS="=" ;ORS=""};/\[END/ {print"\n"} !/\[END/ && !/\[BEGIN/ {print $2" "}' test)


while read line; do

     worker_exec $line -update | tee output.log

done <<< "$VARS"

Hope this helps :) 希望这可以帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM