Skip to content

Instantly share code, notes, and snippets.

@parleer
Last active January 1, 2021 19:46
Show Gist options
  • Select an option

  • Save parleer/762207d2176332dcc77fccb746d09e75 to your computer and use it in GitHub Desktop.

Select an option

Save parleer/762207d2176332dcc77fccb746d09e75 to your computer and use it in GitHub Desktop.
readarray for Bash <4.0
# Attempt to support older BASH without mapfile/readarray
if ! type -t readarray >/dev/null; then
# Very minimal readarray implementation using read.
readarray() {
# _exit "readarray function"
local cmd opt t v=MAPFILE
while [ -n "$1" ]; do
case "$1" in
-h|--help) echo "minimal substitute readarray for older bash"; exit; ;;
-r) shift; opt="$opt -r"; ;;
-t) shift; t=1; ;;
-u)
shift;
if [ -n "$1" ]; then
opt="$opt -u $1";
shift
fi
;;
*)
if [[ "$1" =~ ^[A-Za-z_]+$ ]]; then
v="$1"
shift
else
echo -en "${C_BOLD}${C_RED}Error: ${C_RESET}Unknown option: '$1'\n" 1>&2
exit
fi
;;
esac
done
cmd="read $opt"
eval "$v=()"
while IFS= eval "$cmd line"; do
line=$(echo "$line" | sed -e "s#\([\"\`]\)#\\\\\1#g" )
eval "${v}+=(\"$line\")"
done
}
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment