Skip to content

Instantly share code, notes, and snippets.

@ormaaj
Last active May 5, 2023 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ormaaj/347794ae24c3f187e0b7fdfebafd9941 to your computer and use it in GitHub Desktop.
Save ormaaj/347794ae24c3f187e0b7fdfebafd9941 to your computer and use it in GitHub Desktop.
Array serializer with eval-based indirection for legacy shells.
#!/usr/bin/env bash
typeset -ga bool=([1]=)
# Usage: in_array name outvar
function fmtarr {
typeset x=1 y max ret=$3
printf -v "$ret" '%s+=(' "$2"
eval -- set -- "\"\${!${1}[@]}\"" "\"\${${1}[@]}\"" || return
((max = $# / 2))
while
printf -v y '[%q]=%q' "${@:x:1}" "${@:x + max:1}"
((x++ < max))
eval -- "${ret}+=\${y}\${bool[!\$?]+ }\${bool[\$?]+\\)}" \; let "!$?"
do :
done
}
function demo {
typeset -a b a=({a..f})
typeset v
fmtarr a b v
eval -- "$v"
typeset -p b
}
demo
# vim: set ft=bash fenc=utf-8 ff=unix ts=4 noet :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment