简体   繁体   English

BASH - 使用相同“变量”的多个实例读入配置文件

[英]BASH - Read in config file with multiple instances of the same “variable”

I'm trying to read a config file, and then place the "section" of configs into an array in a bash script, and then run a command off that, and then reitterate through the configs again, and continue to do this until the end of the config file. 我正在尝试读取配置文件,然后将配置的“部分”放入bash脚本中的数组中,然后运行该命令,然后再次通过配置重新执行,并继续执行此操作直到配置文件的结尾。

Here's a sample config file: 这是一个示例配置文件:

PORT="5000"
USER="nobody"
PATH="1"
OPTIONS=""

PORT="5001"
USER="nobody"
PATH="1"
OPTIONS=""

PORT="5002"
USER="nobody"
PATH="1"
OPTIONS=""

I want the bash script to read in the first "section", bring it into the script, and run the following: 我希望bash脚本在第一个“section”中读取,将其带入脚本,然后运行以下命令:
scriptname -p $PORT -u $USER -P $PATH -o $OPTIONS

HOWEVER, I want it to, based on how many "sections" there are in the config file, to take each iteration of a "section", and run the command with its corresponding configuration settings and apply it to the final command. 但是,我希望它根据配置文件中有多少“部分”来进行“部分”的每次迭代,并运行带有相应配置设置的命令并将其应用于最终命令。 So if it were to read in the config file from above, the output would be: 因此,如果要从上面读取配置文件,输出将是:

scriptname -p $PORT -u $USER -P $PATH -o $OPTIONS
scriptname -p $PORT -u $USER -P $PATH -o $OPTIONS
scriptname -p $PORT -u $USER -P $PATH -o $OPTIONS

Which in turn would look like: 反过来看起来像:

scriptname -p 5000 -u nobody -P 1 -o ""
scriptname -p 5001 -u nobody -P 1 -o ""
scriptname -p 5002 -u nobody -P 1 -o ""

Thanks in advance. 提前致谢。

#!/bin/bash

if [[ $# -ne 1 ]]; then
    echo "Usage: $0 script.cfg" >&2
    exit 1
fi

function runscript() {
    scriptname -p $PORT -u $USER -P $PATH -o $OPTIONS
}

while read LINE; do
    if [[ -n $LINE ]]; then
        declare "$LINE"
    else
        runscript
    fi
done < "$1"

runscript

If you want to run the scripts in the background simultaneously, try this: 如果要同时在后台运行脚本,请尝试以下操作:

function runscript() {
    nohup scriptname -p $PORT -u $USER -P $PATH -o $OPTIONS &> /dev/null &
}

The & at the end makes them run in the background and nohup ensures they're not killed when the shell exits. &最后使它们在后台运行, nohup确保它们在shell退出时不会被杀死。 The net effect is to turn the scripts into daemons so they'll run continuously in the background regardless of what happens to the parent script. 最终效果是将脚本转换为守护进程,这样无论父脚本发生什么,它们都会在后台连续运行。

#!/bin/bash

awk 'BEGIN{ FS="\n";RS=""}
{
  for(i=1;i<=NF;i++){
   gsub(/.[^=]*=|\042/,"",$i)
  }
  print "scriptname -p "$1" -u "$2" -P "$3" -o "$4
}' file | bash

Assuming there is only one empty line between sections: 假设各部分之间只有一条空行:

cat <yourfile> | while read ; do
    if [ -z "$REPLY" ] ; then
        scriptname -p $PORT -u $USER -P $PATH -o "$OPTIONS" 
    else
        eval "$REPLY" # NOTE: eval is evil
    fi
done

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

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