Search code examples
bashfor-loopini

Bash - looping through INI sections


my question is about how to read an ini file with a number of sections and feed the section values into variables in a loop.

Here's my batch.ini file

[section1]
val1='/home/test/'
val2='-i -200 -j 400%'

[section2]
val1='/home/test2/'
val2='-i -320 -j 333%'

[section3]
val1='/home/test3/'
val2='-i -223 -j 555%'

In my bash script I’d like to loop through the sections one at a time and assign the values to variables in my bash script. My pseudocode would be like this:

for sectionx = 1 to (number of sections)
do
   my_var1=sectionx(val1)
   my_var2=sectionx(val2)
   echo $my_var1 
   echo $my_var2 
done

Output:

/home/test/
-i -200 -j 400%
/home/test2/
-i -320 -j 333%
/home/test3/
-i -223 -j 555%

Solution

  • If you need to read .ini files in bash, I suggest you use an already implemented solution, for example Bash ini parser by rudimeier works perfectly.

    There are also other options, like shini or the parser by albfan.

    Using the one by rudimeier you will get all the values in bash variables named accordingly.

    For example for your ini

    [section1]
    val1='/home/test/'
    val2='-i -200 -j 400%'
    
    [section2]
    val1='/home/test2/'
    val2='-i -320 -j 333%'
    
    [section3]
    val1='/home/test3/'
    val2='-i -223 -j 555%'
    

    You will get the following bash variables:

    INI__ALL_SECTIONS='section1 section2 section3'
    INI__ALL_VARS='INI__section1__val1 INI__section1__val2 INI__section2__val1 INI__section2__val2 INI__section3__val1 INI__section3__val2'
    INI__NUMSECTIONS=3
    
    INI__section1__val1=/home/test/
    INI__section1__val2='-i -200 -j 400%'
    INI__section2__val1=/home/test2/
    INI__section2__val2='-i -320 -j 333%'
    INI__section3__val1=/home/test3/
    INI__section3__val2='-i -223 -j 555%'
    

    With this you can iterate over sections and variables, for example:

    for section in $INI__ALL_SECTIONS; do 
      echo "Variables in $section:"; 
      for var in `declare | grep "^INI__"$section"__"`; do 
        echo $var; 
      done; 
    done;
    

    Will yield:

    Variables in section1:
    INI__section1__val1=/home/test/
    INI__section1__val2='-i -200 -j 400%'
    
    Variables in section2:
    INI__section2__val1=/home/test2/
    INI__section2__val2='-i -320 -j 333%'
    
    Variables in section3:
    INI__section3__val1=/home/test3/
    INI__section3__val2='-i -223 -j 555%'