3

I am writing a bash script that has a configuration file. The configuration file will have sets of mode and mtu values. There can be zero or as many sets as the user defines. The bash script will source the configuration file.

This is going to stay a very simple program, so I don't need to get really fancy with it.

Each set can be defined by an alphanumeric string (it's a /dev/ name, without the /dev/).

Then, in each set, there's a mode, and an mtu value.

My thought is to create an /etc/ conf file in the format:

ib0_mode=connected
ib0_mtu=65520

Or, for another system:

inf0_mode=connected
inf0_mtu=65520
inf1_mode=datagram
inf1_mtu=2044

Once I know the variable names, I can handle parsing the values and doing the rest.

But, how does a bash script handle not knowing exactly what names there will be?

Do I need to add to the conf:

devices=('inf0' 'inf1')

Or, is that not needed?

If this is added, how do you use a variable name with prefix of a variable name, and suffix hard-coded like "_mode" and "_mtu"?

3

Assuming you are using bash 4.0 or greater, you might want to consider using associative arrays. You can do the following in the config file:

# myscript.rc
mode[inf0]=connected
mtu[inf0]=65520
mode[inf1]=datagram
mtu[inf1]=2044

And then your script would do something like this:

# myscript.sh
declare -A mode
declare -A mtu

source myscript.rc

for mode_idx in ${!mode[@]}; do
    echo "mode[$mode_idx] is ${mode[$mode_idx]}"
done

for mtu_idx in ${!mtu[@]}; do
    echo "mtu[$mtu_idx] is ${mtu[$mtu_idx]}"
done

Note that the list of indices to these arrays is gained from ${!mode[@]}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.