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
On this page
- Querying JSON in the shell with jq
- YAML with yq: extract, edit in place, hand off to jq
- When a script has outgrown Bash
- Worked example: port a health check to Python and keep its exit codes
- Check your understanding
- Apply it
- Review prompt
Lessons of Scripting Basics
- Anatomy of a script: shebang, arguments and exit codes Concept · 15 min
- Control flow you will actually use: tests, case, loops, functions, read and command substitution Worked example · 25 min
- Quoting, strict mode, tracing with set -x and failing loudly Worked example · 20 min
- Lab: an idempotent backup job with logging and a schedule Lab · 30 min
- Beyond Bash: jq, yq and porting a script to Python Worked example · 25 min
- Check: review and repair a fragile script Knowledge check · 8 questions
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.envwalks down nested objects. A missing key is not an error, it printsnull;// "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:
-rprints 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.
# 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}'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 realjqon it. It uses jq syntax exactly, prints JSON unless you add-y(or-Y, which also keeps most comments and styles), and allows-ionly 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:
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-debianyq --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)"'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-debianSelecting 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:
$ 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/-x03. 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.
#!/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"#!/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:
getoptsand the usage check becomeargparse;parser.error()prints the usage line and exits with2, the same code argparse uses for a bad option.curl --max-timebecomesurlopen(..., timeout=...). Without it, the port could hang where the Bash version gave up.- curl's exit codes (
22for an HTTP error with-f,28for a timeout,7for a refused connection) become exceptions.HTTPErrormust be caught beforeURLError, because it is a subclass of it. jqbecomesjson.loads, andset -ebecomes exceptions you catch on purpose. Anything you do not catch prints a traceback and exits with1, which is why every expected failure is handled explicitly.exit Nbecomesreturn Nfrommain()and onesys.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.
"""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()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=$?"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=3The 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
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; checkyq --versionfirst). - 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.pyand 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.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.