Last active
December 18, 2020 02:40
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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