Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Worked example · 25 min · revision 3

Beyond Bash: jq, yq and porting a script to Python

Extract and edit JSON and YAML with jq and yq (and tell the two yq tools apart), recognise when a script has outgrown Bash, and port a health check to Python with argparse, timeouts and the same exit codes.

Contentsand lesson path

What you will learn

  • Automate a recurring task (backup, cleanup or health check) that runs unattended on a schedule and logs its outcome.
  • Extract fields from JSON and YAML with jq and yq, and port a script that has outgrown Bash to Python with argument parsing, HTTP calls with timeouts, error handling and exit codes.

Prerequisites: Linux CLI

01. Querying JSON in the shell with jq

APIs, cloud CLIs and Kubernetes print JSON and YAML, not lines of text. grep, sed and awk work line by line, so they break as soon as keys change order, indentation changes or a value moves into a nested list. Use a tool that parses the format. For JSON that tool is jq, which takes a filter and applies it to its input:

  • Fields: .metadata.labels.env walks down nested objects. A missing key is not an error, it prints null; // "unknown" supplies a fallback. Indexing a value of the wrong type, such as a string, is an error (Cannot index string with string ...), and the ? operator suppresses exactly that error.
  • Arrays: .items[] turns an array into a stream of its elements, so the next filter runs once per element.
  • Filtering: select(.status == "failed") keeps only the elements for which the condition is true.
  • Raw output: -r prints strings without quotes, ready for a shell variable: url=$(jq -r .endpoint config.json).
  • Building JSON: jq -n --arg host "$HOST" '{host: $host}' escapes the value correctly, which string concatenation does not.
Bash · Processing structured JSON streams with jq
# Sample API JSON payload containing service status list
PAYLOAD='{
  "services": [
    {"name": "auth", "healthy": true},
    {"name": "database", "healthy": false}
  ]
}'

# Extract names of unhealthy services as raw text
echo "${PAYLOAD}" | jq -r \
  '.services[] | select(.healthy == false) | .name'

# Construct a new valid JSON payload safely using args
jq -n --arg env "production" --argjson replicas 3 \
  '{environment: $env, target_replicas: $replicas}'
Expected output (jq 1.8)
database
{
  "environment": "production",
  "target_replicas": 3
}

02. YAML with yq: extract, edit in place, hand off to jq

For YAML, such as Kubernetes manifests, Compose files and CI workflows, use yq. Be careful: two different tools are called yq, and both now have version numbers starting with 4.

  • mikefarah/yq is a single Go binary from GitHub releases or package managers such as Homebrew and Snap. It has its own jq-like expression language, edits files in place with -i, and tries to keep comments and formatting (not in every case).
  • kislyuk/yq is a Python package (pip install yq) that converts YAML to JSON and runs the real jq on it. It uses jq syntax exactly, prints JSON unless you add -y (or -Y, which also keeps most comments and styles), and allows -i only together with one of those.

Commands copied from the web often fail because the other yq is installed. Run yq --version first: mikefarah's prints its GitHub URL, kislyuk's prints its own version and then jq's. The examples below use mikefarah yq v4.54.3 on this deploy.yaml:

YAML · deploy.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  labels:
    app: web
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: app
          image: ghcr.io/example/web:1.4.2
          ports:
            - containerPort: 8080
        - name: log-shipper
          image: docker.io/timberio/vector:0.55.0-debian
Terminal · mikefarah yq
yq --version
yq '.spec.template.spec.containers[0].image' deploy.yaml
yq '.spec.template.spec.containers[] | select(.name == "app") | .image' deploy.yaml
yq -i '.spec.replicas = 5' deploy.yaml && yq '.spec.replicas' deploy.yaml
yq -o=json '.spec.template.spec.containers' deploy.yaml |
  jq -r '.[] | "\(.name) \(.image)"'
Expected output
yq (https://github.com/mikefarah/yq/) version v4.54.3
ghcr.io/example/web:1.4.2
ghcr.io/example/web:1.4.2
5
app ghcr.io/example/web:1.4.2
log-shipper docker.io/timberio/vector:0.55.0-debian

Selecting the container by name, rather than by position [0], keeps working when someone adds a sidecar in front of it. -i rewrites the file, so commit or copy it first. -o=json hands the data to jq when a filter needs jq features. With the Python yq installed instead, the read command runs because it is also valid jq, but it prints a JSON string in quotes unless you add -r, and the in-place edit fails:

Expected output (kislyuk yq 4.4.5)
$ yq --version
yq 4.4.5
jq-1.8.2
$ yq -i '.spec.replicas = 5' deploy.yaml
yq: -i/--in-place can only be used with -y/-Y/-t/-T/-x

03. When a script has outgrown Bash

Bash is good glue: it starts a few programs, pipes their output and checks exit codes. It gets fragile when a script needs real data structures (nested maps and lists), several API calls with pagination, retries and error handling, decimal arithmetic ((( )) handles integers only), parallel work with a limit, or unit tests. Many teams treat a script of more than about 100 to 150 lines of logic as a hint to move to Python or Go. The size itself matters less than these needs.

When you port, keep the interface the same: the arguments, the output and, above all, the exit codes, because the scheduler, CI job or monitoring check that calls the script decides what to do from them.

04. Worked example: port a health check to Python and keep its exit codes

Here is a small Bash health check and its Python port. Both promise the same exit-code contract: 0 healthy, 1 the service answered but is unhealthy (an HTTP error status or a body whose status is not ok), 2 bad usage, 3 no answer (connection refused or timeout). A monitoring system can then page for 1 but retry 3.

Bash · health.sh (before)
#!/usr/bin/env bash
# health.sh [-t SECONDS] URL
# Exit codes: 0 healthy, 1 unhealthy, 2 usage error, 3 no answer (refused or timeout)
set -euo pipefail

timeout=5
while getopts 't:' opt; do
  case $opt in
    t) timeout=$OPTARG ;;
    *) echo "usage: health.sh [-t SECONDS] URL" >&2; exit 2 ;;
  esac
done
shift $((OPTIND - 1))
url=${1:-}
if [[ ! $url =~ ^https?:// ]]; then
  echo "usage: health.sh [-t SECONDS] URL (http:// or https://)" >&2
  exit 2
fi

rc=0
body=$(curl -fsS --max-time "$timeout" "$url" 2>/dev/null) || rc=$?
case $rc in
  0) ;;
  22) echo "unhealthy: $url returned an HTTP error status" >&2; exit 1 ;;
  *) echo "no answer from $url (curl exit $rc)" >&2; exit 3 ;;
esac

status=$(jq -r '.status // "missing"' <<< "$body" 2>/dev/null) || status="not JSON"
if [[ $status != ok ]]; then
  echo "unhealthy: status is $status" >&2
  exit 1
fi
echo "healthy: $url"
Python · health.py (after)
#!/usr/bin/env python3
"""health.py [-t SECONDS] URL: the Python port of health.sh, same exit codes."""
import argparse
import json
import sys
import urllib.request
from urllib.error import HTTPError, URLError

HEALTHY, UNHEALTHY, USAGE, NO_ANSWER = 0, 1, 2, 3  # argparse itself exits with 2


def check(url: str, timeout: float) -> int:
    try:
        with urllib.request.urlopen(url, timeout=timeout) as response:
            body = response.read()
    except HTTPError as exc:  # a subclass of URLError, so it must come first
        print(f"unhealthy: {url} returned HTTP {exc.code}", file=sys.stderr)
        return UNHEALTHY
    except (URLError, TimeoutError) as exc:  # refused, DNS failure or timeout
        print(f"no answer from {url} ({getattr(exc, 'reason', exc)})", file=sys.stderr)
        return NO_ANSWER
    try:
        status = json.loads(body).get("status", "missing")
    except (ValueError, AttributeError):  # not JSON, or JSON that is not an object
        status = "not JSON"
    if status != "ok":
        print(f"unhealthy: status is {status}", file=sys.stderr)
        return UNHEALTHY
    print(f"healthy: {url}")
    return HEALTHY


def main() -> int:
    parser = argparse.ArgumentParser(description="Check one HTTP health endpoint.")
    parser.add_argument("url")
    parser.add_argument("-t", "--timeout", type=float, default=5.0)
    args = parser.parse_args()
    if not args.url.startswith(("http://", "https://")):
        parser.error("URL must start with http:// or https://")  # exits with 2
    return check(args.url, args.timeout)


if __name__ == "__main__":
    sys.exit(main())

Each Bash idea has a direct Python equivalent:

  • getopts and the usage check become argparse; parser.error() prints the usage line and exits with 2, the same code argparse uses for a bad option.
  • curl --max-time becomes urlopen(..., timeout=...). Without it, the port could hang where the Bash version gave up.
  • curl's exit codes (22 for an HTTP error with -f, 28 for a timeout, 7 for a refused connection) become exceptions. HTTPError must be caught before URLError, because it is a subclass of it.
  • jq becomes json.loads, and set -e becomes exceptions you catch on purpose. Anything you do not catch prints a traceback and exits with 1, which is why every expected failure is handled explicitly.
  • exit N becomes return N from main() and one sys.exit(main()), which keeps the functions testable.

To compare both versions, run them against a tiny local server with a healthy, an unhealthy and a slow endpoint. Start it in the background, keep its process ID, wait until it answers (a fixed sleep 1 is not always enough for Python to start), and stop it by that PID when you are done. The server ignores a client that hangs up before the slow reply is sent; without that except, it would print a BrokenPipeError traceback into your terminal.

Python · fake_api.py
"""fake_api.py: a local test server with a healthy, an unhealthy and a slow endpoint."""
import json
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

ROUTES = {"/ok": (200, "ok", 0), "/down": (503, "down", 0), "/slow": (200, "ok", 3)}


class Handler(BaseHTTPRequestHandler):
    def do_GET(self) -> None:
        code, status, delay = ROUTES.get(self.path, (404, "not found", 0))
        time.sleep(delay)
        body = json.dumps({"status": status}).encode()
        try:
            self.send_response(code)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        except (BrokenPipeError, ConnectionResetError):
            pass  # the client timed out and hung up (the /slow test)

    def log_message(self, *args) -> None:
        pass


ThreadingHTTPServer(("127.0.0.1", 8765), Handler).serve_forever()
Terminal
chmod +x health.sh
python3 fake_api.py & server_pid=$!
for i in 1 2 3 4 5 6 7 8 9 10; do   # wait up to 5 s until the server answers
  curl -s -o /dev/null http://127.0.0.1:8765/ok && break; sleep 0.5
done
for path in ok down slow; do
  ./health.sh -t 1 "http://127.0.0.1:8765/$path"; echo "bash exit=$?"
  python3 health.py -t 1 "http://127.0.0.1:8765/$path"; echo "python exit=$?"
done
kill "$server_pid"
./health.sh -t 1 http://127.0.0.1:8765/ok; echo "bash exit=$?"
python3 health.py -t 1 http://127.0.0.1:8765/ok; echo "python exit=$?"
Expected output (Python 3.12, curl 7.81, jq 1.8)
healthy: http://127.0.0.1:8765/ok
bash exit=0
healthy: http://127.0.0.1:8765/ok
python exit=0
unhealthy: http://127.0.0.1:8765/down returned an HTTP error status
bash exit=1
unhealthy: http://127.0.0.1:8765/down returned HTTP 503
python exit=1
no answer from http://127.0.0.1:8765/slow (curl exit 28)
bash exit=3
no answer from http://127.0.0.1:8765/slow (timed out)
python exit=3
no answer from http://127.0.0.1:8765/ok (curl exit 7)
bash exit=3
no answer from http://127.0.0.1:8765/ok ([Errno 111] Connection refused)
python exit=3

The messages differ a little, but every exit code matches, which is the part callers depend on. Both also reject a file:// URL with exit code 2: urlopen would otherwise read a local file. One difference is not visible here: when systemd or Kubernetes stops the job with SIGTERM, Python ends at once without running finally blocks unless you install a handler such as signal.signal(signal.SIGTERM, lambda *_: sys.exit(143)).

05. Check your understanding

Practice check · 3 questions

jq, yq and Python port check

Three questions on jq, yq and the Python port.

Q1. What does `jq '.metadata.annotations.owner'` print for the input `{"metadata": {}}`?
Q2. On a CI runner, `yq -i '.spec.replicas = 3' deploy.yaml` fails with `yq: -i/--in-place can only be used with -y/-Y/-t/-T/-x`. On your laptop the same command works. What is the most likely cause?
Q3. Why does the lesson's `health.py` reject `file:///etc/passwd` with a usage error (exit code 2)?
Practice only: not graded, not saved, not evidence.

06. Apply it

Finish this skill's practice task with the tools from this lesson:

  • Move the list of URLs into a YAML file and read it with yq '.urls[]' checks.yaml (mikefarah yq; check yq --version first).
  • Port the URL checks to Python with argparse, a timeout on every request and the same exit codes as the Bash version.
  • Run both versions against fake_api.py and compare the exit codes for each endpoint before you replace the Bash script.

07. Review prompt

Without looking back: what do .items[], select() and -r each do in jq? How do you find out which yq is installed, and what does -i do in mikefarah yq? Name three signs that a script has outgrown Bash. In the port, which Python feature replaces curl --max-time, why must HTTPError be caught before URLError, and why do the exit codes matter more than the messages?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check