[Solved] reading properties from ini file in a bash script


It can be done pretty easily using Awk, just do the below to store the contents in a bash array.

read -p "Enter object to get properties for: " objectname
all_properties=($(awk -F '=' -v input="${objectname}" '$1 ~ input{flag=1; next} $1 ~ /\[object/{flag=0; next} flag && NF {split($0,arr,"="); print arr[2] }  config.ini))

Now loop the array to print the properties,

for property in "${all_properties[@]}"; do
    printf "%s\n" "$property"
done

(or) just

printf "%s\n" "${all_properties[@]}"

The Awk command works as follows:-

  1. Getting the user input in a variable and passing to Awk using the -v syntax and doing a regex match $1 ~ input to match the line containing user input, say object1
  2. I am enabling a flag to start marking lines from this line on-wards and resetting the flag once the next object starts, see $1 ~ /\[object/{flag=0; next}
  3. The condition flag && NF takes care of processing only non-empty lines and only property values after the requested object.
  4. Now on the selected lines, using the split() function in Awk, we can extract the value of property and print it, which will be later stored in the array.

Put the line with read and the line below as shown in a bash script with she-bang set to #!/bin/bash and run it.

E.g. in a complete script as

#!/usr/bin/bash
read -p "Enter object to get properties for: " objectname
all_properties=($(awk -F '=' -v input="${objectname}" '$1 ~ input{flag=1; next} $1 ~ /\[object/{flag=0; next} flag && NF {split($0,arr,"="); print arr[2] }' config.ini ))

printf "%s\n" "${all_properties[@]}"

A few sample runs on the script.

$ bash script.sh
Enter object to get properties for: object1
propertyA

$ bash script.sh
Enter object to get properties for: object2
property1
property2

$ bash script.sh
Enter object to get properties for: object3
propertyxya

4

solved reading properties from ini file in a bash script