Config File Parsing in Shell
Level 5249 keystrokes
Reads a key=value config file line by line into an associative array, skipping comment and empty lines and trimming spaces around keys and values. The output assumes config.ini contains host=localhost.
Shell code
# Associative array to hold the settings (Bash 4+)1declare -A config# IFS='=' splits at the first =; value gets the rest of the line2while IFS='=' read -r key value; do # Skip comment lines (optional spaces, then #)3 [[ $key =~ ^[[:space:]]*# ]] && continue # Skip empty lines4 [[ -z $key ]] && continue # xargs trims spaces around the text (it also strips quotes)5 key=$(echo "$key" | xargs)6 value=$(echo "$value" | xargs) # Store the pair in the array7 config["$key"]="$value"# Feed config.ini to the loop as input8done < config.ini# Read a setting by its key9echo "Host: ${config[host]}"Output
Host: localhost
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Shell code and how often they appear.
"× 10$× 9[× 8]× 8=× 6&× 4-× 3:× 3'× 2(× 2