# A variable to contain the configs provided manually or via function calls declare -g -A CONFIG ########################## # Function: load_section # Usage: This will return the section of a aggragate config file # # EX: # [TEST_BEGIN] # test=1 # test2=34 # [TEST_END] # # load_section /path/to/config TEST [OPT_VAR] function load_section () { local SECTION_NAME=${1:?"$FUNCNAME: No section name was provided"} local FILE=${2:?"$FUNCNAME: No file was provided"} local BUFFER_ARRAY BUFFER_STRING local SECTION_BEGIN="\[${SECTION_NAME}_BEGIN\]" local SECTION_END="\[${SECTION_NAME}_END\]" if [[ $3 != "" ]]; then local OPT_VAR_PROVIDED=1 local -n OPT_OUTPUT_VAR=$3 fi if [[ $FILE == '-' ]]; then FILE=/dev/stdin elif [[ ! -f $FILE ]]; then echo "$FUNCNAME: $FILE does not exist" exit fi ## Loading contents, since it will clear /dev/stdin on a read (in the case that it is being used to provide the content) local FILE_CONTENTS=$(<$FILE) if ! grep -q "$SECTION_BEGIN" <<< "$FILE_CONTENTS" || ! grep -q "$SECTION_END" <<< "$FILE_CONTENTS"; then echo "$FUNCNAME: Either the begin or end $SECTION_NAME section was missing from the file ($FILE) provided" exit fi mapfile -t BUFFER_ARRAY <<< "$FILE_CONTENTS" local CAN_READ=0 for ((i=0; i < ${#BUFFER_ARRAY[@]}; i++)); do if [[ ${BUFFER_ARRAY[$i]} =~ ^$SECTION_BEGIN ]]; then CAN_READ=1 continue elif [[ ${BUFFER_ARRAY[$i]} =~ ^$SECTION_END ]]; then break elif [[ $CAN_READ -eq 1 ]]; then BUFFER_STRING+="\n${BUFFER_ARRAY[$i]}" fi done if [[ $OPT_VAR_PROVIDED -eq 1 ]]; then OPT_OUTPUT_VAR=$( echo -e "$BUFFER_STRING" ) else echo -e "$BUFFER_STRING" fi } ############################## # Function: load_config_ini # Usage: You would call this function to load an ini formated config file into the global CONFIG associative array # or into a Associative Array variable you provide as the second argument function load_config_ini () { local FILE=${1:?"$FUNCNAME: No file was provided"} if [[ $2 != "" ]]; then local -n CONFIG_VAR=${2} else local -n CONFIG_VAR=CONFIG fi if ! declare -p ${!CONFIG_VAR} 2>/dev/null | grep -q 'declare -A'; then echo "The output variable (${!CONFIG_VAR}) provided was either not an Associative array or was not declared." echo "Please declare your variable correctly as 'declare -A ${!CONFIG_VAR}'" exit fi if [[ ! -f $FILE ]]; then echo "$FUNCNAME: $FILE does not exist" exit fi local SECTION_REGEX='\[(\S+)\]' local KEY_VAL_REGEX='[[:space:]]*(\S+)[[:space:]]*=[[:space:]]*(.+)' local -a BUFFER_ARRAY local SECTION="" KEY="" VAL="" mapfile -t BUFFER_ARRAY <$FILE for ((i=0; i < ${#BUFFER_ARRAY[@]}; i++)); do LINE=${BUFFER_ARRAY[$i]} if [[ $LINE =~ ^$SECTION_REGEX ]]; then SECTION=${BASH_REMATCH[1],,} elif [[ $LINE =~ ^$KEY_VAL_REGEX ]]; then KEY=${BASH_REMATCH[1],,} VAL=${BASH_REMATCH[2]} if [[ $SECTION != "" ]]; then CONFIG_VAR["$SECTION.$KEY"]=$VAL else CONFIG_VAR["$KEY"]=$VAL fi fi done }