#!/bin/bash set -eo pipefail # To read a value from the INI file # Assume the INI file is formatted like: # [section] # key=value # Function to read a value from an INI-style file read_ini() { local INI_FILE="$1" local SECTION="$2" local KEY="$3" # Use awk to read the specific section and key awk -F '=' "/^\[$SECTION\]/ {section=1} section==1 && /^$KEY=/ {print \$2; exit}" "$INI_FILE" } # To write or update a value in the INI file # Function to set a value in an INI-style file write_ini() { local INI_FILE="$1" local SECTION="$2" local KEY="$3" local VALUE="$4" # Create the INI file if it doesn't exist if [ ! -f "$INI_FILE" ]; then touch "$INI_FILE" fi # Check if the key already exists if grep -q "^\[$SECTION\]" "$INI_FILE"; then if grep -q "^$KEY=" "$INI_FILE"; then # If the key exists, update it sed -i "/^\[$SECTION\]/, /^\[/ { /^$KEY=/ s/=.*/=$VALUE/ }" "$INI_FILE" else # If the key does not exist, add it under the section sed -i "/^\[$SECTION\]/a $KEY=$VALUE" "$INI_FILE" fi else # If the section does not exist, add the section and the key echo -e "\n[$SECTION]\n$KEY=$VALUE" >> "$INI_FILE" fi } # Usage #write_ini "config.ini" "section" "key" "newvalue" #write_ini "config.ini" "newsection" "key" "newvalue" # Usage #value=$(read_ini "config.ini" "section" "key") #echo "$value" #value=$(read_ini "config.ini" "section" "key2") #echo "$value"