GC-301g · Module 1
Output Capture & Exit Codes
3 min read
Capturing output reliably requires understanding the three output streams: stdout carries the model's response, stderr carries diagnostic messages and progress indicators, and the exit code signals success or failure. For automation, always redirect stderr to a log file (2>gemini-err.log) so diagnostic noise does not contaminate your parsed output. Capture stdout into a variable or file, then validate both the exit code and the output content before proceeding.
Exit codes are your first line of defense against silent failures. Exit code 0 means the model produced a response — but not necessarily a correct one. Non-zero codes indicate infrastructure failures: authentication errors, rate limit exhaustion, network timeouts, invalid configuration. Your automation must check exit codes before parsing output. A script that blindly processes stdout after a failed invocation will parse error messages as if they were valid responses — a common and dangerous bug in naive automation.
#!/bin/bash
# Robust output capture with exit code handling
capture_gemini() {
local prompt="$1"
local outfile="$2"
local errfile="${outfile%.json}.err"
gemini -p "$prompt" --output-format json \
> "$outfile" 2> "$errfile"
local rc=$?
if [ $rc -ne 0 ]; then
echo "FAIL [$rc]: $(cat "$errfile")" >&2
return $rc
fi
# Validate JSON structure
if ! jq empty "$outfile" 2>/dev/null; then
echo "FAIL: Invalid JSON in $outfile" >&2
return 1
fi
return 0
}
# Usage
if capture_gemini "Analyze src/api/ for dead code" results/dead-code.json; then
echo "Analysis complete: $(jq '.response | length' results/dead-code.json) chars"
else
echo "Analysis failed — check results/dead-code.err"
exit 1
fi