>_ IzzyLab

Hands-on task

This task is step 5 of the course “JSON, YAML and XML in the terminal”

jq --arg: a parameter from the shell

medium~7 min

/root/users.json holds an array of objects with name and age fields; some names contain spaces and quotes. Write a script /root/age.sh: it takes a name as its first argument and prints that user's age. Don't paste the name into the filter text — pass it to jq as a variable via --arg. Run the script for Bob (bash /root/age.sh Bob) and write the result to /root/age.txt.

What you'll practise:
  • jq
  • --arg
  • variables
  • select
  • parameterization

Topic breakdown

Inserting external values directly into the text of a jq filter is dangerous (special characters, quotes, injections) and awkward because of shell escaping. The right way is to declare variables: --arg name value creates a string $name, --argjson name JSON a value of any type (number, object). Inside the filter they are available as $name. This makes jq scripts reusable and safe — the same filter works with different parameters passed in from outside, without string concatenation.

What's checked

  1. Bob's correct age is written
  2. the script takes the name from the argument
  3. a name with quotes doesn't break the filter

What it looks like