Skip to content

Instantly share code, notes, and snippets.

@kaerimichi
Forked from splaspood/bash_iniparse.sh
Last active December 15, 2019 02:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kaerimichi/7caab9e6d6951964f6b4 to your computer and use it in GitHub Desktop.
Save kaerimichi/7caab9e6d6951964f6b4 to your computer and use it in GitHub Desktop.
cfg.parser () {
fixed_file=$(cat $1 | sed 's/ = /=/g') # fix ' = ' to be '='
IFS=$'\n' && ini=( $fixed_file ) # convert to line-array
ini=( ${ini[*]//;*/} ) # remove comments
ini=( ${ini[*]/#[/\}$'\n'cfg.section.} ) # set section prefix
ini=( ${ini[*]/%]/ \(} ) # convert text2function (1)
ini=( ${ini[*]/=/=\( } ) # convert item to array
ini=( ${ini[*]/%/ \)} ) # close array parenthesis
ini=( ${ini[*]/%\( \)/\(\) \{} ) # convert text2function (2)
ini=( ${ini[*]/%\} \)/\}} ) # remove extra parenthesis
ini[0]='' # remove first element
ini[${#ini[*]} + 1]='}' # add the last brace
eval "$(echo "${ini[*]}")" # eval the result
}
# parse the config file called 'myfile.ini', with the following
# contents::
# [sec2]
# var2='something'
cfg.parser 'myfile.ini'
# enable section called 'sec2' (in the file [sec2]) for reading
cfg.section.sec2
# read the content of the variable called 'var2' (in the file
# var2=XXX). If your var2 is an array, then you can use
# ${var[index]}
echo "$var2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment