0

STATUS QUO

i have an external properties file, where a couple of variables are stored. one of these has a list of values (min 1 value, max X values).

when declaring this single list within the shell script, it would look like this:

NODES=(
    "node"
    "node-2"
    "node-3"
)

I read the values from the properties file like this:

# checks, if file exists and is readable
file="./properties.credo"
if [ ! -r "$file" ]
then
    echo "fatal: properties file $file not found / readable."
    exit 2
fi

# loads properties into variables 
. $file
[[ -z "$VALUEA" ]] && echo "fatal: VALUEA not specified in .credo" && exit 2
...

PROBLEM

When defining the NODES values in the properties like this:

NODES=node,node-2,node-3

... and reading with that:

...
[[ -z "$NODES" ]] && echo "fatal: NODES not specified in .credo" && exit 2
...

... it will be read from the file as a single string node,node-2,node-3, but not as a list or one-dimensional array.

bivvo
  • 61
  • 6

1 Answers1

1

Beware! This is dangerous as the config file can contain PATH=/some/path and the script can then execute commands over which you have no control.

You can use read -a to populate an array. Set IFS to the separator and send the values read from the file to read's standard input.

#! /bin/bash
file=$1

IFS== read var values < "$file"
IFS=, read -a $var <<< "$values"

echo "${NODES[@]}"

For a multiline config, I tried the following:

nodes=node1,node2,node3
servers=server1,server2

and modified the script to loop over the input:

#! /bin/bash
file=$1

while IFS== read var values ; do
    IFS=, read -a $var <<< "$values"
done < "$file"
echo "${nodes[@]}"
echo "${servers[@]}"

You might need to skip over lines that don't follow the var=val1,val2,... pattern.

choroba
  • 231,213
  • 25
  • 204
  • 289
  • Understood, thx. I've taken your code, but get an empty output for NODES. Only the first line of FILE is read. The last property in the file is the one "NODES" with the list. Do I have to loop through somehow? – bivvo Jan 04 '22 at 09:07
  • Yes, if there are more lines, you need to loop over them. – choroba Jan 04 '22 at 09:10
  • Can you pls help me and show, how that would look like? Please – bivvo Jan 04 '22 at 09:11
  • 1
    Answer updated. – choroba Jan 04 '22 at 09:35
  • btw. i do not understand the moderation of questions here. just someone takes a part of the question, links it and closes it. independent from if it answers the whole question or not. that's weird and annoying. :-/ – bivvo Jan 04 '22 at 09:54