Skip to content

Instantly share code, notes, and snippets.

@rawiriblundell
Created December 12, 2019 11:19
Show Gist options
  • Save rawiriblundell/36f9317d18366a4ca29c96a28e0c80f6 to your computer and use it in GitHub Desktop.
Save rawiriblundell/36f9317d18366a4ca29c96a28e0c80f6 to your computer and use it in GitHub Desktop.
A function to provide the most basic mapfile capability for pre-bash4
# A portability function for older systems that don't have the mapfile builtin
if ! command -v mapfile >/dev/null 2>&1; then
mapfile() {
local _arrName i IFS
unset MAPFILE
set -f # Turn off globbing
set +H # Prevent parsing of '!' via history substitution
# We use the behaviour of '-t' by default, so if it's given, skip it
while getopts ":t" flags; do
case "${flags}" in
(t) :;; # Only here for compatibility
(*) :;; # Dummy action
esac
done
shift "$(( OPTIND - 1 ))"
# If an argument is left, it's our array name, otherwise this
# function will export an array named MAPFILE (as the real 'mapfile' does)
_arrName="${1}"
# Read all of the input
i=0
while IFS=$'\n' read -r; do
MAPFILE[i]="${REPLY}"
((i++))
done
# Sometimes there's a trailing line in a while read loop, if so catch it
[[ "${REPLY}" ]] && MAPFILE[i]="${REPLY}"
export MAPFILE
# Finally, rename the array if required
# I would love to know a better way to handle this
if [[ -n "${_arrName}" ]]; then
# shellcheck disable=SC2034
eval "${_arrName}=( \"\${MAPFILE[@]}\" )"
fi
# Set f and H back to normal
set +f
set -H
}
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment