Skip to content

Instantly share code, notes, and snippets.

@dantrim
Last active June 11, 2021 22:44
Show Gist options
  • Save dantrim/0523075b651509a27d339f4e6f2c326c to your computer and use it in GitHub Desktop.
Save dantrim/0523075b651509a27d339f4e6f2c326c to your computer and use it in GitHub Desktop.
Updates an integer value of a field at a specific path
#!/bin/bash
# This is an example showing how to update a value of a specified key
# (that is potentially nested) in a JSON file using shell variables
# in some shell script. For example, some utility for updatiing in-place
# a common set of fields in a JSON configuration file.
# In the snippet below, we assume that the input is a key ("register_name")
# in some nested JSON object whose path is "RD53B.GlobalConfig".
filename=${1}
register_name=${2}
new_value=${3}
# Notes:
# - We use jq's "--arg" to specify the jq variables using the shell-defined variables,
# and then use the newly-defined variables within the jq filter
# - The first line in the jq filter (with the select(...) command) is a check that the
# specified key ("register_name"/"register") actually exists. If it does, then its value
# will be updated. If it does not, no updates will occur.
# - The jq arguments are always handled as strings, so we use the "tonumber" utility
# to convert the value to a number-type in the output JSON object.
jq --arg register "${register_name}" \
--arg value "${new_value}" \
'. | select(.RD53B.GlobalConfig[$register] != null)
| .RD53B.GlobalConfig[$register] = ($value|tonumber)' \
${filename} > tmp.json && mv tmp.json ${filename}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment