Configuration Files
Key-Value Config
Reading a Setting
Many simple config files use name=value lines. A script can read each line and keep the value for the key it needs.
Program
Play the script to scan fixed config text for a selected key.
parse_key_values.sh
#!/usr/bin/env bash
config=$'host=local\nport=8080\ndebug=false'
selected_key=
selected_value=""
while IFS="=" read -r key value; do
if [[ "$key" == "$selected_key" ]]; then
selected_value=$value
fi
done <<< "$config"
echo "$selected_key=$selected_value"
#!/usr/bin/env bash
config=$'host=local\nport=8080\ndebug=false'
selected_key=
selected_value=""
while IFS="=" read -r key value; do
if [[ "$key" == "$selected_key" ]]; then
selected_value=$value
fi
done <<< "$config"
echo "$selected_key=$selected_value"
#!/usr/bin/env bash
config=$'host=local\nport=8080\ndebug=false'
selected_key=
selected_value=""
while IFS="=" read -r key value; do
if [[ "$key" == "$selected_key" ]]; then
selected_value=$value
fi
done <<< "$config"
echo "$selected_key=$selected_value"
IFS
`IFS="="` makes `read` split each line around the equals sign.
read loop
`while read ...; do` processes one config line per iteration.
selected key
The `if` keeps only the value whose key matches the selected setting.