Last active
September 7, 2024 22:54
-
-
Save GongT/96894ccb324b8cd814bac06bd51306d4 to your computer and use it in GitHub Desktop.
protect bash array with json
This file contains 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
function json_array() { | |
if [[ $# -eq 0 ]]; then | |
echo '[]' | |
fi | |
# --ascii-output if no base64 | |
jq --null-input --compact-output --slurp '$ARGS.positional' --args "$@" | |
} | |
function json_array_get_back() { | |
local -i SIZE i | |
local VARNAME="$1" JSON="$2" | |
local -a ARR=() | |
SIZE=$(echo "$JSON" | jq --compact-output '.|length') | |
for ((i = 0; i < SIZE; i++)); do | |
ARR+=("$(echo "$JSON" | jq --compact-output --raw-output ".[$i]")") | |
done | |
eval "$VARNAME=(\"\${ARR[@]}\")" | |
} |
This file contains 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
STR=$'\x1Bfrom\tthe world' | |
BASH_ARR=( | |
printf | |
"say: %s! %s\n" | |
"$STR" | |
'🥺' | |
) | |
JSON=$(json_array "${BASH_ARR[@]}") | |
echo "json = $JSON" >&2 | |
ENCODE=$(echo "$JSON" | base64 --wrap=0 -) | |
echo "encoded = $ENCODE" >&2 | |
echo "$ENCODE" |
This file contains 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
declare -a NEW_ARR=() | |
json_array_get_back NEW_ARR "$(base64 -d)" | |
"${NEW_ARR[@]}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment