Skip to content

Instantly share code, notes, and snippets.

@Akianonymus
Last active June 5, 2021 01:58
Show Gist options
  • Save Akianonymus/91f28140f9219aa64cecbf7a5fcfb17c to your computer and use it in GitHub Desktop.
Save Akianonymus/91f28140f9219aa64cecbf7a5fcfb17c to your computer and use it in GitHub Desktop.
Parse key=val config file
parse_config() {
_config_file="${1:?Error: Profile config file}"
# check if the config file accessible
[ -r "${_config_file}" ] || {
printf "%s\n" "Error: Given config file ( ${_config_file} ) is not readable."
return 1
}
# Setting 'IFS' tells 'read' where to split the string.
while IFS='=' read -r key val; do
# Skip Lines starting with '#'
# Also skip lines if key and val variable is empty
{ [ -n "${key}" ] && [ -n "${val}" ] && [ -n "${key##\#*}" ] ;} || continue
# trim all leading white space
key="${key#${key%%[![:space:]]*}}"
val="${val#${val%%[![:space:]]*}}"
# trim all trailing white space
key="${key%${key##*[![:space:]]}}"
val="${val%${val##*[![:space:]]}}"
# '$key' stores the key and '$val' stores the value.
# Throw a warning if cannot export the variable
export "${key}=${val}" 2>/dev/null ||
printf "%s\n" "Warning: ${key} is not a valid variable name."
done < "${_config_file}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment