Skip to content

Instantly share code, notes, and snippets.

@mtthlm
Created February 5, 2022 01:13
Show Gist options
  • Save mtthlm/b87e4c0abd8a200b116bf1f4f446ba06 to your computer and use it in GitHub Desktop.
Save mtthlm/b87e4c0abd8a200b116bf1f4f446ba06 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
set -o errexit -o nounset
IFS=$'\n' read -r -d '' < <(
while [[ $# -gt 0 ]]
do
if [[ "$1" =~ ^([a-zA-Z0-9_]+)=(.+)$ ]]
then printf -- 'declare -- %s=\(%s|tostring);' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}"
fi
shift
done
) || true
jq --raw-output "@sh \"${REPLY}\""
@mtthlm
Copy link
Author

mtthlm commented Feb 5, 2022

Usage:

IFS=$'\n' read -r -d '' <<'EOF' || true
{
  "name": "Matt",
  "emails": [
    "matt.helm@mehnet.io"
  ]
}
EOF

eval "$(./jq-shvars.sh USER_NAME='.name' USER_EMAIL='.emails[0]' <<<"$REPLY")"

declare -p USER_NAME USER_EMAIL
#declare -- USER_NAME="Matt"
#declare -- USER_EMAIL="matt.helm@mehnet.io"

This little utility makes it easy to parse out JSON values into shell variables.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment