Published on

jq -r

Let’s break this shell line down piece by piece, from right to left, and then put it all together.

value=$(jq -r '.value // empty' "$CONFIG_FILE")

1️⃣ $( ... ) — command substitution

value=$( ... )
  • $(...) means run the command inside and capture its output
  • The output is assigned to the shell variable value

So whatever text the command prints to stdout becomes the value of value.


2️⃣ jq — JSON processor

jq is a command-line tool used to parse and query JSON files.

Here it is used to extract a field from a JSON file.


3️⃣ -r — raw output

jq -r ...
  • -r means raw output
  • Without -r, jq outputs JSON strings with quotes:
"value"
  • With -r, jq outputs plain text:
value

This is important for shell scripting, because you usually don’t want quotes.


4️⃣ '.value // empty' — jq filter

This is the most important part.

.value

  • Accesses the key named value at the top level of the JSON

Example JSON:

{
  "value": "hello"
}

.value"hello"


// empty — fallback operator

  • // is jq’s default / fallback operator

  • It means:

    “If the left side is null or missing, use the right side instead”

empty is a jq builtin that outputs nothing at all.

So:

JSON caseResult
"value" existsprints its value
"value": nullprints nothing
"value" missingprints nothing

This avoids errors or "null" showing up.


5️⃣ "$CONFIG_FILE" — input file

  • $CONFIG_FILE is a shell variable containing a path to a JSON file
  • The quotes protect against spaces in the filename

Example:

CONFIG_FILE=config.json

🔁 Put it all together

This line means:

Read a JSON file, extract the .value field, print it as plain text if it exists, otherwise print nothing, and store the result in the shell variable value.


✅ Example walkthrough

JSON file

{
  "value": "production"
}

Result

value="production"

JSON file (missing key)

{
  "env": "production"
}

Result

value=""

(no error, no null, just empty)


  • Safe for missing keys
  • No noisy "null"
  • No extra quotes
  • Works well with set -e
  • Ideal for config files in CI/CD or scripts