You are not logged in.

#21 2019-03-08 07:24:37

johnraff
nullglob
From: Nagoya, Japan
Registered: 2015-09-09
Posts: 12,549
Website

Re: bash script function to parse config files

johnraff wrote:

I'll have a look round some config files of apps we use like network-manager, lightdm etc and see if there's any kind of consensus.

Time to tie this up.
Examples
avahi-daemon.conf has this line:

browse-domains=0pointer.de, zeroconf.org

A space-and-comma-separated list. neutral
/etc/lightdm/users.conf has:

[UserList]
hidden-users=nobody nobody4 noaccess

Again, space-separated list.
Wavering a bit, but allowing entries like this (with no surrounding quotes) while still allowing comments, will make the parsing regex(s) less robust IMO, so at this point I think I'm going to insist that unquoted entries must be single words, with no spaces. If future developers find this too restrictive for their scripts, lets loosen it up then.

So the current functions would now look like this:

# These functions need bash.

# Usage: parse_config <file> [<default array name>]

# If no default array name is given, it defaults to 'config'.
# If there are [section] headers in file, following entries will be
#  put in array of that name.

# Config arrays may exist already and will appended to or overwritten.
# If preexisting array is not associative, function exits with error.
# New arrays will be created as needed, and remain in the environment.
parse_config(){
    [[ -f $1 ]] || { echo "$1 is not a file." >&2;return 1;}
    if [[ -n $2 ]]
    then
        local -n config_array=$2
    else
        local -n config_array=config
    fi
    declare -Ag ${!config_array} || return 1
    local line key value section_regex entry_regex
    section_regex="^[[:blank:]]*\[([[:alpha:]_][[:alnum:]_]*)\][[:blank:]]*(#.*)?$"
    entry_regex="^[[:blank:]]*([[:alpha:]_][[:alnum:]_-]*)[[:blank:]]*=[[:blank:]]*('[^']+'|\"[^\"]+\"|[^#[:blank:]]+)[[:blank:]]*(#.*)*$"
    while read -r line
    do
        [[ -n $line ]] || continue
        [[ $line =~ $section_regex ]] && {
            local -n config_array=${BASH_REMATCH[1]}
            declare -Ag ${!config_array} || return 1
            continue
        }
        [[ $line =~ $entry_regex ]] || continue
        key=${BASH_REMATCH[1]}
        value=${BASH_REMATCH[2]#[\'\"]} # strip quotes
        value=${value%[\'\"]}
        config_array["${key}"]="${value}"
    done < "$1"
}

# Usage: parse_config_vars <file>
# No arrays, just read variables individually.
# Preexisting variables will be overwritten.

parse_config_vars(){
    [[ -f $1 ]] || { echo "$1 is not a file." >&2;return 1;}
    local line key value entry_regex
    entry_regex="^[[:blank:]]*([[:alpha:]_][[:alnum:]_-]*)[[:blank:]]*=[[:blank:]]*('[^']+'|\"[^\"]+\"|[^#[:blank:]]+)[[:blank:]]*(#.*)*$"
    while read -r line
    do
        [[ -n $line ]] || continue
        [[ $line =~ $entry_regex ]] || continue
        key=${BASH_REMATCH[1]}
        value=${BASH_REMATCH[2]#[\'\"]} # strip quotes
        value=${value%[\'\"]}
        declare -g "${key}"="${value}"
    done < "$1"
}

OP will also be updated.

Last edited by johnraff (2020-12-26 07:31:35)


...elevator in the Brain Hotel, broken down but just as well...
( a boring Japan blog (currently paused), now on Bluesky, there's also some GitStuff )

Introduction to the Bunsenlabs Boron Desktop

Offline

#22 2019-03-10 19:52:49

ohnonot
...again
Registered: 2015-09-29
Posts: 5,592

Re: bash script function to parse config files

nice, thanks again, I dropped it into my weather script and it seems to be working ok (first try).

Last edited by ohnonot (2021-05-31 19:03:44)

Offline

#23 2019-03-17 08:57:36

johnraff
nullglob
From: Nagoya, Japan
Registered: 2015-09-09
Posts: 12,549
Website

Re: bash script function to parse config files

^Thanks!
'ini' built fine on Buster and seems to do its job.

There were a couple of Lintian messages, and I noticed that no man page was generated, although the code seems to be providing for one. Also, I wonder if the package name 'ini' might be a bit short, potentially intruding on other namespaces?

More important, though, is that as it is it doesn't seem to do exactly what I want:

Variables that don't come under a [section] are ignored.

The main point is that I'd like to have a set of default key/value pairs already set in the script calling 'ini', and possible config files under /usr/share, /etc and ~/.config parsed in turn to look for any variables to overwrite. I can't see any way to do this without a lot of shell code and multiple calls to 'ini'. Am I missing something?


...elevator in the Brain Hotel, broken down but just as well...
( a boring Japan blog (currently paused), now on Bluesky, there's also some GitStuff )

Introduction to the Bunsenlabs Boron Desktop

Offline

#24 2019-03-18 12:05:29

johnraff
nullglob
From: Nagoya, Japan
Registered: 2015-09-09
Posts: 12,549
Website

Re: bash script function to parse config files

This all started when I was looking at what people recommended for shell scripts' config files. The most common advice was just to source shell fragments like:

key1=val1
key2=val2

but the problem with that is that the "config" file can contain any arbitary code which the calling script will just run as-is, no questions asked. Otherwise there are a couple of big complicated parsers on GitHub. I thought it could be done more simply... roll

Anyway the two functions in the OP will fetch variables - or arrays - only, so a certain improvement in safety. I wanted something easy to use for developers and reasonably intuitive for users. (Indeed, there's no standard for ini, conf or rc files.)

It now occurs to me, though, that allowing the config file to overwrite any variable means giving it freedom to change any variable in the calling script's environment - not only those the dev had in mind. Maybe the second variables-only function parse_config_vars() should be abandoned in favour of the first one parse_config() which at least packs the values away in a named array. Even that one leaves the window open that any section can be defined in the parsed config file and an array created with that name, populated with key-value pairs. If that array already exists, the keys will be overwritten, even if it's something in the environment, not directly connected with the calling script. (eg BASH_ALIASES although that one might not be relevant to scripts.)

So the only safe way might be to ignore sections and put key/value pairs in an associative array named by the calling script?

I guess even that might be enough for a lot of purposes?


...elevator in the Brain Hotel, broken down but just as well...
( a boring Japan blog (currently paused), now on Bluesky, there's also some GitStuff )

Introduction to the Bunsenlabs Boron Desktop

Offline

#25 2019-03-18 12:37:23

Bearded_Blunder
Dodging A Bullet
From: Seat: seat0; vc7
Registered: 2015-09-29
Posts: 1,146

Re: bash script function to parse config files

Some things are tough to protect against, boils down to "don't run untrustworthy stuff", can change any variable my user has access to and run arbitrary code from openbox autostart if I put silly stuff there too.  I commend the effort, but frankly if someone's gotten bad script onto your machine the game's lost. Just put a shell script replacing arbitrary program in ~/bin & what's in it gets run every bit as unchecked as a script sourced for variables, and being earlier in path gets run before the actual intended program/script.

You could do some unfortunate things with a script named apt that typically gets called using sudo.

I've only ever really viewed this as some protection against user errors in a config.. if you're wanting to protect against potentially malicious things the user didn't put there themselves, it's probably time to concede defeat.


Blessed is he who expecteth nothing, for he shall not be disappointed...
If there's an obscure or silly way to break it, but you don't know what.. Just ask me

Offline

#26 2019-03-20 05:50:56

johnraff
nullglob
From: Nagoya, Japan
Registered: 2015-09-09
Posts: 12,549
Website

Re: bash script function to parse config files

Agreed, basically. Only thing is that these functions are intended to be libraries that any developer can pull into their script, so they ought to be as robust as possible IMO. We don't know what kind of script they might be used in, whether run as root or not... Of course the dev writing the script is supposed to be on top of that stuff...

Anyway, I've added an option to check all variables against a whitelist before overwriting them. (Only the straight-variable parse_config_vars() function so far.) It still works as before without a list, but if the name of an associative array is passed as $2, then variable names will be checked against the keys of that array and only overwritten if they are in the list.

Set up the array in the calling script something like this

declare -A checklist
for var in some_setting squidliness frobnacity
do
    checklist[$var]=1 # 1 can be any string
done

Then parse the config file(s) with:

parse_config_vars /path/to/configfile checklist

Only the three variables in checklist will be overwritten (if mentioned in configfile).

---
It doesn't take a lot of extra code in the function, this at the start:

    local check=false
    if [[ -n $2 ]]
    then
        local -n list=$2 # list is a nameref to $2
        [[ "$(declare -p ${!list} 2>/dev/null)" = 'declare -A'* ]] || { echo "$2 is not an associative array." >&2; return 1;}
        check=true
    fi

and this just before writing out the new variable value:

[[ $check = true && ${list[$key]:-X} = X ]] && continue

So the whole new function looks like this:

# Usage: parse_config_vars <file> [<checklist array name>]
# No arrays, just read variables individually.
# Preexisting variables will be overwritten.
# If name of checklist associative array is provided, then
# only variables which are keys of that array will be (over)written.

parse_config_vars(){
    local check=false
    if [[ -n $2 ]]
    then
        local -n list=$2
        [[ "$(declare -p ${!list} 2>/dev/null)" = 'declare -A'* ]] || { echo "$2 is not an associative array." >&2; return 1;}
        check=true
    fi
    [[ -f $1 ]] || { echo "$1 is not a file." >&2; return 1;}
    local line key value entry_regex
    entry_regex="^[[:blank:]]*([[:alpha:]_][[:alnum:]_]*)[[:blank:]]*=[[:blank:]]*('[^']+'|\"[^\"]+\"|[^#[:blank:]]+)[[:blank:]]*(#.*)*$"
    while read -r line
    do
        [[ -n $line ]] || continue
        [[ $line =~ $entry_regex ]] || continue
        key=${BASH_REMATCH[1]}
        [[ $check = true && ${list[$key]:-X} = X ]] && continue
        value=${BASH_REMATCH[2]#[\'\"]} # strip quotes
        value=${value%[\'\"]}
        declare -g "${key}"="${value}"
    done < "$1"
}

As I said, the checklist is optional - the function should still work as before too.

If no-one reports any issues I'll do the same with the other function for section names, and update the OP.


...elevator in the Brain Hotel, broken down but just as well...
( a boring Japan blog (currently paused), now on Bluesky, there's also some GitStuff )

Introduction to the Bunsenlabs Boron Desktop

Offline

#27 2020-03-09 02:44:24

johnraff
nullglob
From: Nagoya, Japan
Registered: 2015-09-09
Posts: 12,549
Website

Re: bash script function to parse config files

[ replying to now-deleted comment]

^Thanks for looking at this!
To be honest, at the time I was working on these scripts, I had the goal of being able to make user config files for bl-exit. That (python) version has now been replaced with something simpler which doesn't need config parsing.

So these two functions just went into semi-retirement till the day some need might arise...

Very happy to help dig into this now, in the hope that one or both of them might be useful in the future.
Give me a day or two...


...elevator in the Brain Hotel, broken down but just as well...
( a boring Japan blog (currently paused), now on Bluesky, there's also some GitStuff )

Introduction to the Bunsenlabs Boron Desktop

Offline

#28 2020-12-26 07:26:10

johnraff
nullglob
From: Nagoya, Japan
Registered: 2015-09-09
Posts: 12,549
Website

Re: bash script function to parse config files

Sorry misko, I still haven't revisited these functions - till today.

But what needs doing right now is a tweak to the regular expression that looks for the ini file keys: I left out the possibility of a dash. Considering how many ini keys contain dashes, a pretty silly mistake, but

entry_regex="^[[:blank:]]*([[:alpha:]_][[:alnum:]_]*)[[:blank:]]*=[[:blank:]]*('[^']+'|\"[^\"]+\"|[^#[:blank:]]+)[[:blank:]]*(#.*)*$"

should be

entry_regex="^[[:blank:]]*([[:alpha:]_][[:alnum:]_-]*)[[:blank:]]*=[[:blank:]]*('[^']+'|\"[^\"]+\"|[^#[:blank:]]+)[[:blank:]]*(#.*)*$"

In all the above functions.
ie this bit

[[:alnum:]_]*

needed a dash adding to the character group.

I'll update the OP now, for my own records if nothing else.


...elevator in the Brain Hotel, broken down but just as well...
( a boring Japan blog (currently paused), now on Bluesky, there's also some GitStuff )

Introduction to the Bunsenlabs Boron Desktop

Offline

#29 2023-05-24 13:20:46

MegaV0lt
Member
Registered: 2023-05-24
Posts: 5

Re: bash script function to parse config files

Found this treat a few days ago. I use it on my vdr to parse conf file. Great work!

I had to change the regex to match also --key=value

I added - to both in the first group

([[:alpha:]_-][[:alnum:]_-]*)

Another change i made to catch -k value
I changed = to [\s=]

Finaly my

entry_regex="^[[:blank:]]*([[:alpha:]_-][[:alnum:]_-]*)[[:blank:]]*[\s=][[:blank:]]*('[^']+'|\"[^\"]+\"|[^#[:blank:]]+)[[:blank:]]*(#.*)*$"

So maybe someone else also finds it useful

Last edited by MegaV0lt (2023-05-24 13:27:36)

Offline

#30 2023-05-25 09:09:26

MegaV0lt
Member
Registered: 2023-05-24
Posts: 5

Re: bash script function to parse config files

More changes i made:

section_regex="^[[:blank:]]*\[([[:alpha:]_-][[:alnum:]_-]*)\][[:blank:]]*(#.*)?$"

Also deals wit - and _

Removed second continue because it is not needed at the end of the loop. The Function now looks like:

f_parse_config(){
  # Usage: parse_config <file> [<default array name>]

  # If no default array name is given, it defaults to 'config'.
  # If there are [section] headers in file, following entries will be
  # put in array of that name.

  # Config arrays may exist already and will appended to or overwritten.
  # If preexisting array is not associative, function exits with error.
  # New arrays will be created as needed, and remain in the environment.
  [[ ! -f "$1" ]] && { echo "$1 is not a file." >&2 ; return 1 ;}
  local -n config_array="${2:-config}"
  declare -Ag "${!config_array}" || return 1
  local line key value section_regex entry_regex
  section_regex="^[[:blank:]]*\[([[:alpha:]_-][[:alnum:]_-]*)\][[:blank:]]*(#.*)?$"
  entry_regex="^[[:blank:]]*([[:alpha:]_-][[:alnum:]_-]*)[[:blank:]]*[\s=][[:blank:]]*('[^']+'|\"[^\"]+\"|[^#[:blank:]]+)[[:blank:]]*(#.*)*$"
  while read -r line ; do
    [[ -z "$line" ]] && continue
    [[ "$line" =~ $section_regex ]] && {
      local -n config_array="${BASH_REMATCH[1]}"
      declare -Ag "${!config_array}" || return 1
      continue
    }
    [[ "$line" =~ $entry_regex ]] && {
      key="${BASH_REMATCH[1]}"
      value="${BASH_REMATCH[2]#[\'\"]}" # strip quotes
      value="${value%[\'\"]}"
      config_array["$key"]="$value"
    }
  done < "$1"
}

Last edited by MegaV0lt (2023-05-30 15:50:09)

Offline

#31 2023-05-27 16:58:51

jr2
android
Registered: 2017-12-24
Posts: 91

Re: bash script function to parse config files

Hi MegaV0it, thanks for having a look at this. Right now I have only a cellphone. When I'm back home I'll comment properly on your contributions. smile


normal service will be resumed as soon as possible

Offline

#32 2023-05-30 15:49:31

MegaV0lt
Member
Registered: 2023-05-24
Posts: 5

Re: bash script function to parse config files

I also changed now

  if [[ -n "$2" ]] ; then
    local -n config_array="$2"
  else
    local -n config_array=config
  fi

to

local -n config_array="${2:-config}"

Offline

#33 2023-06-18 05:06:07

johnraff
nullglob
From: Nagoya, Japan
Registered: 2015-09-09
Posts: 12,549
Website

Re: bash script function to parse config files

OK looking at these one at a time:

MegaV0lt wrote:

I had to change the regex to match also --key=value

What case did you find where keys in a config ini or key file are preceded with a double-dash like that?

Another change i made to catch -k value
I changed = to [\s=]

Again '-k value' is never found in an ini/config file - the equals sign is compulsory to separate the key from the value. Spaces might appear later in the value.

These feel like things that might be passed as arguments to a command:
command --key=value -k value
Parsing a command line is a different task from parsing a file.

The syntax of config/ini/key files is widely defined in different ways*, so I had to try to find something that most scripters could use easily. Coping with unusual cases might make the regex very long...

* eg Freedesktop Desktop files:
https://specifications.freedesktop.org/ … ml#entries
http://www.crategus.com/books/cl-cffi-g … -file.html

freedesktop wrote:

Only the characters A-Za-z0-9- may be used in key names.

So I've already gone beyond that in allowing the underbar _ too (which is allowed in variable names).

In fact, that dash might possibly cause trouble later if it appears in a variable name. That feels like a possible bug that needs to be looked at, because the dash does often appear in key names.

I also limited the first character of the key to [[:alpha:]_] because it might later become a variable name and in bash the only acceptable characters are those:
https://www.gnu.org/software/bash/manua … index-name

So a little more thought is needed on how dashes should be handled...

Last edited by johnraff (2023-06-18 05:10:38)


...elevator in the Brain Hotel, broken down but just as well...
( a boring Japan blog (currently paused), now on Bluesky, there's also some GitStuff )

Introduction to the Bunsenlabs Boron Desktop

Offline

#34 2023-06-18 05:29:41

johnraff
nullglob
From: Nagoya, Japan
Registered: 2015-09-09
Posts: 12,549
Website

Re: bash script function to parse config files

MegaV0lt wrote:

More changes i made:

section_regex="^[[:blank:]]*\[([[:alpha:]_-][[:alnum:]_-]*)\][[:blank:]]*(#.*)?$"

Also deals wit - and _

To be honest, I'm even less sure whether we should be allowing dashes in section names.

Remember, most of the time, the config file is being parsed by a script written by the same person who wrote the file. They can choose reasonable key names and section names, even if we have no control over what users might put in the value section.

Removed second third continue because it is not needed at the end of the loop. The Function now looks like:

    [[ "$line" =~ $entry_regex ]] && {
        key="${BASH_REMATCH[1]}"
        value="${BASH_REMATCH[2]#[\'\"]}" # strip quotes
        value="${value%[\'\"]}"
        config_array["$key"]="$value"
    }
done < "$1"
}

Original code:

    [[ $line =~ $entry_regex ]] || continue
    key=${BASH_REMATCH[1]}
    value=${BASH_REMATCH[2]#[\'\"]} # strip quotes
    value=${value%[\'\"]}
    config_array["${key}"]="${value}"
done < "$1"

I think these two are logically equivalent, so it's more a matter of taste. I prefer the appearance of the original code. smile


...elevator in the Brain Hotel, broken down but just as well...
( a boring Japan blog (currently paused), now on Bluesky, there's also some GitStuff )

Introduction to the Bunsenlabs Boron Desktop

Offline

#35 2023-06-18 05:36:22

johnraff
nullglob
From: Nagoya, Japan
Registered: 2015-09-09
Posts: 12,549
Website

Re: bash script function to parse config files

MegaV0lt wrote:

I also changed now

  if [[ -n "$2" ]] ; then
    local -n config_array="$2"
  else
    local -n config_array=config
  fi

to

local -n config_array="${2:-config}"

That's a nice refinement - thanks, I'll add it to the OP. cool


...elevator in the Brain Hotel, broken down but just as well...
( a boring Japan blog (currently paused), now on Bluesky, there's also some GitStuff )

Introduction to the Bunsenlabs Boron Desktop

Offline

#36 2023-06-18 06:29:50

MegaV0lt
Member
Registered: 2023-05-24
Posts: 5

Re: bash script function to parse config files

In the .conf-files of VDR there are --key=value and -k val and that was the reason for my change. See:

www.vdr-wiki.de/wiki/index.php/VDR_Optionen
www.yavdr.org/documentation/0.6/de/ch05s01.html

I agree that dash in keyname mut not be used. Will change my script…
I also make the for section name

PS: Also note that variables should be quoted.

I post my script when i am at home for reference. Thank you for your answer!

Offline

#37 2023-06-18 06:47:49

johnraff
nullglob
From: Nagoya, Japan
Registered: 2015-09-09
Posts: 12,549
Website

Re: bash script function to parse config files

MegaV0lt wrote:

In the .conf-files of VDR there are --key=value and -k val and that was the reason for my change. See:

www.vdr-wiki.de/wiki/index.php/VDR_Optionen
www.yavdr.org/documentation/0.6/de/ch05s01.html

I agree that dash in keyname mut not be used. Will change my script…

Interesting - it's very unusual to see something like '--shutdown=***' in a config file. Usually it would be 'shutdown=***'

Actually, it's all quite complicated and badly defined. The Freedesktop standard for example says "Only the characters A-Za-z0-9- may be used in key names" meaning that the dash is OK but the underscore not. But bash variable names can hold underscores but not dashes. A9h6pD1.gif

People writing scripts with config files should probably best stick to simple names.

You're right that variables should nearly always be quoted. There are a few cases when it's unnecessary, like usually inside [[ * ]] or when defining a variable v2=$v1, but it's usually safest to quote.


...elevator in the Brain Hotel, broken down but just as well...
( a boring Japan blog (currently paused), now on Bluesky, there's also some GitStuff )

Introduction to the Bunsenlabs Boron Desktop

Offline

#38 2023-06-18 15:40:43

DeepDayze
Like sands through an hourglass...
From: In Linux Land
Registered: 2017-05-28
Posts: 1,897

Re: bash script function to parse config files

johnraff wrote:
MegaV0lt wrote:

In the .conf-files of VDR there are --key=value and -k val and that was the reason for my change. See:

www.vdr-wiki.de/wiki/index.php/VDR_Optionen
www.yavdr.org/documentation/0.6/de/ch05s01.html

I agree that dash in keyname mut not be used. Will change my script…

Interesting - it's very unusual to see something like '--shutdown=***' in a config file. Usually it would be 'shutdown=***'

Actually, it's all quite complicated and badly defined. The Freedesktop standard for example says "Only the characters A-Za-z0-9- may be used in key names" meaning that the dash is OK but the underscore not. But bash variable names can hold underscores but not dashes. https://i.imgur.com/A9h6pD1.gif

People writing scripts with config files should probably best stick to simple names.

You're right that variables should nearly always be quoted. There are a few cases when it's unnecessary, like usually inside [[ * ]] or when defining a variable v2=$v1, but it's usually safest to quote.

Agreed..simple key=value entries (with no extraneous special characters) in configs are easiest to debug issues with.

Many apps put their startup parameters here too and need some sanity checking to verify if they are in accepted ranges.

Last edited by DeepDayze (2023-06-18 15:42:31)


Real Men Use Linux

Offline

#39 2023-06-19 07:44:00

MegaV0lt
Member
Registered: 2023-05-24
Posts: 5

Re: bash script function to parse config files

The vdr config file format is given and i can not change. I ended up with replacing - with _ in 'key' so the function now is:

f_parse_config(){
  # Usage: f_parse_config <file> [<default array name>]

  # If no default array name is given, it defaults to 'config'.
  # If there are [section] headers in file, following entries will be
  # put in array of that name.

  # Config arrays may exist already and will appended to or overwritten.
  # If preexisting array is not associative, function exits with error.
  # New arrays will be created as needed, and remain in the environment.
  [[ ! -f "$1" ]] && { echo "$1 is not a file." >&2 ; return 1 ;}
  local -n config_array="${2:-config}"
  declare -Ag "${!config_array}" || return 1
  local line key value section_regex entry_regex
  section_regex="^[[:blank:]]*\[([[:alpha:]_][[:alnum:]_-]*)\][[:blank:]]*(#.*)?$"
  entry_regex="^[[:blank:]]*([[:alpha:]_-][[:alnum:]_-]*)[[:blank:]]*[\s=][[:blank:]]*('[^']+'|\"[^\"]+\"|[^#[:blank:]]+)[[:blank:]]*(#.*)*$"
  while read -r line ; do
    [[ -z "$line" ]] && continue
    [[ "$line" =~ $section_regex ]] && {
      local -n config_array="${BASH_REMATCH[1]}"
      declare -Ag "${!config_array}" || return 1
      continue
    }
    [[ "$line" =~ $entry_regex ]] && {
      key="${BASH_REMATCH[1]//-/_}"     # Replace all '-' with '_'
      value="${BASH_REMATCH[2]#[\'\"]}" # Strip quotes
      value="${value%[\'\"]}"
      config_array["$key"]="$value"
    }
  done < "$1"
}

Here is a example what i do with the values:

for key in "${!vdr[@]}" ; do  # vdr ist der Abschnitt in der conf ([vdr])
  #echo -e "Key: $key \t Value: ${vdr[$key]}"  # Debug
  case "$key" in  # '-' are replaced with '_'
    _l|__log)   LOG_LEVEL="${vdr[$key]}" ;;
    _v|__video) VIDEO="${vdr[$key]}" ;;
  esac
done

# Werte in die /etc/vdr/conf.d/vdr übertragen
COMMENT="# Wird mit Wert aus $VDR_CONF überschrieben!"
sed -i -e "s|LOG_LEVEL=.*|LOG_LEVEL=${LOG_LEVEL:-3}  ${COMMENT}|" \
  -e "s|VIDEO=.*|VIDEO=${VIDEO:-/video}  ${COMMENT}|" "$VDR_CFG"

Offline

#40 2024-05-20 07:59:31

johnraff
nullglob
From: Nagoya, Japan
Registered: 2015-09-09
Posts: 12,549
Website

Re: bash script function to parse config files

johnraff wrote:

I've added an option to check all variables against a whitelist before overwriting them. It still works as before without a list, but if the name of an associative array is passed as $2, then variable names will be checked against the keys of that array and only overwritten if they are in the list.
If no-one reports any issues I'll do the same with the other function for section names, and update the OP.

I updated the second function parse_config_vars() to incorporate the optional whitelist array.
The first function - which puts variable values in arrays according to sections in the config file - has been left unchanged.


...elevator in the Brain Hotel, broken down but just as well...
( a boring Japan blog (currently paused), now on Bluesky, there's also some GitStuff )

Introduction to the Bunsenlabs Boron Desktop

Offline

Board footer

Powered by FluxBB