Search code examples
arraysbashscriptingifs

Parsing a settingsfile in bashscript where some special settings are arrays


I am still quite new to bash scripting and I am somehow stuck. I am looking for a clean and easy way to parse a settingsfile, where some special (and known) settings are arrays.

So the settings file looks like this.

foo=(1 2 3 4)
bar="foobar"

The best solution I came up with so far is:

#!/bin/bash    
while IFS== read -r k v; do
    if [ "$k" = "foo" ]
        then
          IFS=' ' read -r -a $k <<< "$v"
        else
          declare "$k"="$(echo $v | tr -d '""')"
        fi
    done < settings.txt

But I am obviously mixing up array types. As far is I understood and tried out for the bar="foobar" part this actually declares an array, and could be accessed by echo ${bar[0]} but as well as echo $bar. So I thought this would be a indexed array, but the error log clearly states something different:

cannot convert associative to indexed array

Would be glad if somebody could explain me a little bit how to find a proper solution.


Solution

  • Is it safe for you to just source the file?

    . settings.txt
    

    That will insert all the lines of the file as if they were lines of your current script. Obviously, there are security concerns if the file isn't as secure as the script file itself.