Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@leagris
Last active December 18, 2020 02:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leagris/0cb299f95bb3cd14630bd06bf2bb5235 to your computer and use it in GitHub Desktop.
Save leagris/0cb299f95bb3cd14630bd06bf2bb5235 to your computer and use it in GitHub Desktop.
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