-
-
Save kaerimichi/7caab9e6d6951964f6b4 to your computer and use it in GitHub Desktop.
Bash INI parser (http://theoldschooldevops.com/2008/02/09/bash-ini-parser/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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