Created
December 13, 2011 20:34
-
-
Save splaspood/1473761 to your computer and use it in GitHub Desktop.
Parsing INI Files with Bash
This file contains hidden or 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 | |
} | |
cfg.parser '/etc/my.ini' | |
cfg.section.images |
Those interested in even modifying the INI file can refer to this one: https://github.com/albfan/bash-ini-parser which is an enhancement from the same original source. This is under GPL v3.
Other options:
https://github.com/rudimeier/bash_ini_parser
https://github.com/pixelb/crudini
Pleased that people keep finding this gist useful. Thanks @techpavan for the updated source!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @splaspood,
I am using it in script with
#!/bin/sh
and i get error ,`cfg.parser': not a valid identifier
How can i use it in script with
#!/bin/sh