Skip to content

Instantly share code, notes, and snippets.

@ayZagen
Last active September 26, 2023 13:45
Show Gist options
  • Save ayZagen/e7301885b9167f48e416744a8c92e146 to your computer and use it in GitHub Desktop.
Save ayZagen/e7301885b9167f48e416744a8c92e146 to your computer and use it in GitHub Desktop.
Replace simple json values by key with corresponding environment variable using jq
#!/bin/sh
## Install if jq package doesn't exist
if which jq; then echo "jq exists";
else
if which yum; then
yum jq
elif which apt-get; then
apt-get install jq
elif which apk; then
apk add --no-cache jq
else
exit 1;
fi
fi
## Replace
for key in `jq "keys | .[]" $1 | xargs` ; do
eval "_TO_CHECK=\$$key"
if [ "$_TO_CHECK" ]; then
if echo "$_TO_CHECK" | egrep -q '^\-?[0-9]*\.?[0-9]+$'; then ## If it is number
jq ".$key=$_TO_CHECK" $1 > _temp.json && mv _temp.json $1
else
jq ".$key=\"$_TO_CHECK\"" $1 > _temp.json && mv _temp.json $1
fi
fi
done
@ayZagen
Copy link
Author

ayZagen commented Feb 23, 2019

EXAMPLE

// test.json
{
  "NAME":"holderforname",
  "SURNAME":"holderforsurname"
}
$ export NAME="myName"
$ ./replace.sh test.json
$ cat test.json
{
  "NAME":"myName",
  "SURNAME":"holderforsurname"
}

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