- 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 ...
-rmeans 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
valueat the top level of the JSON
Example JSON:
{
"value": "hello"
}
.value → "hello"
// empty — fallback operator
//is jq’s default / fallback operatorIt 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 case | Result |
|---|---|
"value" exists | prints its value |
"value": null | prints nothing |
"value" missing | prints nothing |
This avoids errors or "null" showing up.
5️⃣ "$CONFIG_FILE" — input file
$CONFIG_FILEis 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
.valuefield, print it as plain text if it exists, otherwise print nothing, and store the result in the shell variablevalue.
✅ Example walkthrough
JSON file
{
"value": "production"
}
Result
value="production"
JSON file (missing key)
{
"env": "production"
}
Result
value=""
(no error, no null, just empty)
🧠 Why this pattern is popular
- Safe for missing keys
- No noisy
"null" - No extra quotes
- Works well with
set -e - Ideal for config files in CI/CD or scripts