问题
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.
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: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.
回答1:
#!/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. 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.
回答2:
#!/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
回答3:
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
来源:https://stackoverflow.com/questions/3410306/bash-read-in-config-file-with-multiple-instances-of-the-same-variable