0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Read INI File with Section and Key Parsing

Use a Bash script that reads the INI file line by line, skips comments and empty lines, detects sections with \[section\], and extracts key-value pairs with key=value syntax using while read and case statements.
📋

Examples

Input[general] name=John age=30
OutputSection: general name=John age=30
Input[user] username=alice password=secret [server] ip=192.168.1.1 port=8080
OutputSection: user username=alice password=secret Section: server ip=192.168.1.1 port=8080
Input# comment line [empty] key=value [another] key2=val2
OutputSection: empty key=value Section: another key2=val2
🧠

How to Think About It

To read an INI file in Bash, treat it like a text file. Read it line by line. Ignore empty lines and comments starting with # or ;. When you see a line with square brackets, that marks a section. Save that section name. For lines with an equals sign, split into key and value. Print or store them with the current section. This way, you parse the file logically.
📐

Algorithm

1
Open the INI file for reading line by line.
2
For each line, skip if it is empty or a comment.
3
If the line matches a section header [section], save the section name.
4
If the line contains key=value, extract key and value.
5
Print or store the section, key, and value.
6
Repeat until the end of the file.
💻

Code

bash
#!/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"
Output
Section: general name=John age=30
🔍

Dry Run

Let's trace reading a simple INI file with a section and two keys.

1

Read first line

Line is '[general]', matches section pattern, current_section set to 'general', prints 'Section: general'

2

Read second line

Line is 'name=John', matches key=value pattern, prints 'name=John'

3

Read third line

Line is 'age=30', matches key=value pattern, prints 'age=30'

StepLineActionOutput
1[general]Set current_section='general'Section: general
2name=JohnExtract key='name', value='John'name=John
3age=30Extract 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

Using awk to parse INI
bash
awk '/^\[/{section=substr($0,2,length($0)-2)} /^[^#;].*=/{split($0,a,"="); print section ":" a[1] "=" a[2]}' file.ini
Awk is concise and fast but less readable for beginners.
Using source with sanitized INI
bash
sed -e 's/;.*//' -e 's/#.*//' -e '/^$/d' -e 's/\[\([^]]*\)\]/[\"\1\"]/g' file.ini > temp.sh
source temp.sh
Transforms INI to shell variables but requires careful sanitizing to avoid code injection.

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.

ApproachTimeSpaceBest For
Bash while-read loopO(n)O(1)Simple scripts, beginners
Awk one-linerO(n)O(1)Performance and concise parsing
Source sanitized INIO(n)O(1)When INI can be safely converted to shell variables
💡
Always trim whitespace and ignore comments when reading INI files in Bash.
⚠️
Beginners often forget to handle empty lines and comments, causing parsing errors.