📝 add examples

This commit is contained in:
DrMaxNix 2024-05-31 22:14:53 +02:00
parent 129c0606f1
commit 71bbcd04d2
4 changed files with 89 additions and 0 deletions

View File

@ -1,2 +1,18 @@
# Bash INI
A simple ini parser written in bash
### Usage
```bash
# include the library
source "ini.sh"
# parse a config
ini_parse "config.ini"
# read a value
echo "${ini__section_1[first_value]}"
```
An in-depth example can be found in the `example` folder!

16
example/config.ini Normal file
View File

@ -0,0 +1,16 @@
root_value = 420
[section.1]
first_value=3
second.value = "test"
third-value = 'another test'
[section-2]
new-value.mixed_joiners = "just works!"
another.value = no quotation marks required...
[section.1]
again = "sure!"
first_value="overwritten!"
[section-3]

2
example/other-config.ini Normal file
View File

@ -0,0 +1,2 @@
[sect]
hihi = "hoho"

55
example/script.sh Executable file
View File

@ -0,0 +1,55 @@
#!/bin/bash
set -euo pipefail
## INIT ##
# get script base directory
SCRIPT_PATH=$(readlink -f "${BASH_SOURCE[0]}")
SCRIPT_DIR=$(dirname -- "$SCRIPT_PATH")
# load ini library
source "${SCRIPT_DIR}/../ini.sh"
## PARSE INI CONFIG ##
# `my_conf` is the prefix you can use to refer to this config's values
# defaults to `ini`
ini_parse "${SCRIPT_DIR}/config.ini" my_conf
# if you want to load another config file, you can just use a different name!
ini_parse "${SCRIPT_DIR}/other-config.ini" my_other_conf
## LIST ALL VALUES ##
# `my_conf` is an array of section names
for s in ${my_conf[*]}; do
echo "Section:: $s"
# `my_conf__section_1__key_list` is an array of keys under the section "section_1"
declare -n one_section_key_list="my_conf__${s}__key_list"
# `my_conf__section_1` is an associative array mapping keys to their values for the section "section_1"
declare -n one_section_map="my_conf__${s}"
for k in ${one_section_key_list[*]}; do
echo " Key:: $k"
echo " Value:: ${one_section_map[$k]}"
echo
done
echo
done
## READ CERTAIN VALUES ##
# get value of `first_value` under section `section_1`
echo "my_conf__section_1[first_value]:: ${my_conf__section_1[first_value]}"
# get value of `root_value` under root section (watch out for the triple underscore!)
echo "my_conf___root[root_value]:: ${my_conf___root[root_value]}"
# use bash parameter substitution for default values
echo "my_conf__section_1[third-value]:: ${my_conf__section_1[third-value]:-"<default value>"}"
echo "my_conf__section_1[fourth-value]:: ${my_conf__section_1[fourth-value]:-"<default value>"}"
# access values from other config file
echo "my_other_conf__sect[hihi]:: ${my_other_conf__sect[hihi]}"