Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A shim for Bash's mapfile to support mapping key value pairs into an associative array
#!/usr/bin/env bash
# mapfile_assoc_shim.sh
# If mapfile does not have a -A associative array mode
# then implement it
# Usage:
# include mapfile_assoc_shim.sh
# or
# . mapfile_assoc_shim.bash
#
# Example:
# IFS='=' mapfile -A assoc_array <<<$'key1=value1\nkey2=value2'
#
if ! { mapfile -A _ </dev/null; } 2>/dev/null; then
mapfile() {
local k v d
local -n A=${*: -1:1}
declare -gA "${!A}"
if [ "${*: -2:1}" = -A ]; then
if [ "${*:1:1}" = -d ]; then
d=${*:2:1}
else
d=$'\n'
fi
while read -rd "$d" k v || [ "$k" ]; do
# shellcheck disable=SC2034 # nameref use
[ "$k" ] && A[$k]=$v
done
else
command mapfile "$@"
fi
}
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment