Skip to content

Instantly share code, notes, and snippets.

@deusebio
Created January 14, 2022 22:46
Show Gist options
  • Save deusebio/c8dde51d46c2a74e567d46d3fc7d9209 to your computer and use it in GitHub Desktop.
Save deusebio/c8dde51d46c2a74e567d46d3fc7d9209 to your computer and use it in GitHub Desktop.
Bash function to parse ini configuration files
#!/bin/bash
function iniget() {
if [[ $# -lt 2 || ! -f $1 ]]; then
echo "usage: iniget <file> [--list|<section> [key]]"
return 1
fi
local inifile=$1
if [[ "$2" == "--list" ]]; then
SECTIONS=$(cat "$inifile" | grep "\[" | sed -e "s#\[##g" | sed -e "s#\]##g")
for section in $SECTIONS; do
echo $section
done
return 0
fi
local section=$2
local key
[ $# -eq 3 ] && key=$3
# https://stackoverflow.com/questions/49399984/parsing-ini-file-in-bash
# This awk line turns ini sections => [section-name]key=value
local lines=$(awk '/\[/{prefix=$0; next} $1{print prefix $0}' $inifile)
if [ ! -z $section ]; then
section_lines=$(echo $lines | grep "\[$section\]" | sed -e "s/^\[$section\]//")
fi
if [ ! -z "$key" ]; then
value=$(echo $section_lines | awk -F "=" "/${key}/ {print \$2}")
echo $value
else
echo $section_lines
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment