What is jq in bash

Last updated: April 1, 2026

Quick Answer: jq is a command-line utility used in bash scripts to parse, filter, and transform JSON data from APIs, files, or piped input. It enables bash scripts to work with JSON without requiring external programming languages like Python or Node.js.

Key Facts

Overview

In bash scripting, jq is the go-to tool for JSON processing. When a bash script needs to parse JSON from an API call, manipulate data structures, or extract values for conditional logic, jq provides an elegant solution without leaving the shell environment. This avoids the overhead of launching a full Python interpreter or Node.js runtime.

Basic Bash Usage Patterns

In bash scripts, jq is typically used with command substitution. For example, name=$(curl https://api.example.com/user | jq '.name') fetches JSON and stores the name in a bash variable. Another common pattern is if curl https://api.example.com/status | jq '.healthy' | grep -q 'true'; then to conditionally execute code based on JSON values.

Common Bash and jq Combinations

Practical Examples in Bash

A deployment script might use jq '.version' to extract the application version from a package manifest. A monitoring script could run aws ec2 describe-instances | jq -r '.Reservations[].Instances[].InstanceId' to list all instance IDs for further processing. In CI/CD pipelines, jq extracts build artifacts, deployment targets, and status information from JSON configurations and API responses.

Why jq is Better Than Alternatives in Bash

Using pure bash string manipulation or grep/sed to parse JSON is fragile and error-prone. Bash lacks native JSON parsing, making regex-based approaches unreliable for edge cases like escaped characters or nested structures. jq provides a robust, purpose-built solution that makes bash scripts more reliable, readable, and maintainable when handling JSON data from modern cloud services and APIs.

Related Questions

How do you use jq with curl in a bash script?

Pipe curl output directly to jq: curl https://api.example.com/data | jq '.field'. To store results in a variable, use: result=$(curl https://api.example.com/data | jq '.field'). This is the standard pattern for fetching and parsing API responses in bash scripts.

Can you loop through JSON arrays in bash using jq?

Yes, using jq's raw output mode. For example: jq -r '.items[] | .name' outputs each name on a separate line, which can be piped to a bash while loop. Alternatively, jq supports foreach and recursive functions for more complex iterations.

How do you handle errors in bash when using jq?

Check jq's exit status with $? or use set -e to exit on errors. For defensive scripts, use jq 'has("field")' to verify fields exist, and use jq's try-catch syntax like 'try .field catch null' to handle missing values gracefully.

Sources

  1. jq Official Website and ManualMIT
  2. GNU Bash ManualGNU FDLS