Skip to content

Instantly share code, notes, and snippets.

@roman-lautenschlager
Last active June 7, 2025 18:42
Show Gist options
  • Save roman-lautenschlager/d3827d292b4d94fdd8c78ef3df45e892 to your computer and use it in GitHub Desktop.
Save roman-lautenschlager/d3827d292b4d94fdd8c78ef3df45e892 to your computer and use it in GitHub Desktop.
BASH INI file parser
#!/usr/bin/env bash
inifile="${1}";
# ini file exists
if [[ -f "${inifile}" ]]; then
# file is not empty
if [[ -s "${inifile}" ]]; then
# default section
inisection="main";
# read file line by line
while read -r iniline; do
# line contains section name []
if [[ "${iniline}" =~ ^[[:space:]]*\[[[:alnum:]]+\] ]]; then
# line with section name
inisection=$( echo -e "${iniline}" | tr --delete --complement '[:alnum:]_' );
else
# key/value pair separated by =
if [[ "${iniline}" =~ .+=.+ ]]; then
# remove special characters from key name
inikey=$( echo -n "${iniline%=*}" | tr --delete --complement '[:alnum:]_' );
# delete only leading and trailing spaces from value
inivalue=$( echo -n "${iniline#*=}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' );
# delete only leading and trailing double quotes from value (for BASH)
inivalue=$( echo -n "${inivalue}" | sed -e 's/^["]*//' -e 's/["]*$//' );
# delete only leading and trailing single quotes from value (for SQL)
sqlvalue=$( echo -n "${inivalue}" | sed -e "s/^[']*//" -e "s/[']*$//" );
# replace double quotes with escaped quotes (for BASH)
inivalue=$( echo -n "${inivalue}" | sed -e 's/"/\\"/g' );
# replace single quotes with two single quotes (for SQL)
sqlvalue=$( echo -n "${sqlvalue}" | sed -e "s/'/''/g" );
# output (for BASH)
echo "I_${inisection^^}_${inikey^^}=\"${inivalue}\";";
# output (for SQL)
echo -e "DEFINE I_${inisection^^}_${inikey^^} := '${sqlvalue}';";
echo;
fi
fi
# all lines from ini files, except ; comments
done < <( grep --invert-match --extended-regexp '^[[:space:]]*;' "${inifile}" );
else
echo "file ${inifile} is empty";
exit 1;
fi
else
echo "file ${inifile} not found";
exit 1;
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment