Bash Script to Read INI File with Section and Key Parsing
\[section\], and extracts key-value pairs with key=value syntax using while read and case statements.Examples
How to Think About It
Algorithm
Code
#!/bin/bash ini_file="$1" current_section="" shopt -s extglob while IFS= read -r line || [[ -n "$line" ]]; do # Remove leading/trailing whitespace line="${line##+([[:space:]])}" line="${line%%+([[:space:]])}" # Skip empty lines and comments [[ -z "$line" || "$line" =~ ^[;#] ]] && continue # Check for section if [[ "$line" =~ ^\[(.*)\]$ ]]; then current_section="${BASH_REMATCH[1]}" echo "Section: $current_section" elif [[ "$line" =~ ^([^=]+)=(.*)$ ]]; then key="${BASH_REMATCH[1]}" value="${BASH_REMATCH[2]}" echo "$key=$value" fi done < "$ini_file"
Dry Run
Let's trace reading a simple INI file with a section and two keys.
Read first line
Line is '[general]', matches section pattern, current_section set to 'general', prints 'Section: general'
Read second line
Line is 'name=John', matches key=value pattern, prints 'name=John'
Read third line
Line is 'age=30', matches key=value pattern, prints 'age=30'
| Step | Line | Action | Output |
|---|---|---|---|
| 1 | [general] | Set current_section='general' | Section: general |
| 2 | name=John | Extract key='name', value='John' | name=John |
| 3 | age=30 | Extract key='age', value='30' | age=30 |
Why This Works
Step 1: Skip empty and comment lines
The script ignores lines that are empty or start with # or ; to avoid processing irrelevant data.
Step 2: Detect section headers
Lines matching \[section\] set the current section name, so keys can be grouped logically.
Step 3: Extract key-value pairs
Lines with key=value format are split into key and value using regex, then printed or stored.
Alternative Approaches
awk '/^\[/{section=substr($0,2,length($0)-2)} /^[^#;].*=/{split($0,a,"="); print section ":" a[1] "=" a[2]}' file.inised -e 's/;.*//' -e 's/#.*//' -e '/^$/d' -e 's/\[\([^]]*\)\]/[\"\1\"]/g' file.ini > temp.sh source temp.sh
Complexity: O(n) time, O(1) space
Time Complexity
The script reads the file line by line once, so time grows linearly with file size.
Space Complexity
Uses constant extra space for variables; no large data structures stored.
Which Approach is Fastest?
The Bash while-read loop is simple and efficient for small to medium files; awk is faster for large files but less beginner-friendly.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Bash while-read loop | O(n) | O(1) | Simple scripts, beginners |
| Awk one-liner | O(n) | O(1) | Performance and concise parsing |
| Source sanitized INI | O(n) | O(1) | When INI can be safely converted to shell variables |