Inferensys

Prompt

CLI Pipe and Redirection Behavior Prompt

A practical prompt playbook for using the CLI Pipe and Redirection Behavior Prompt to generate production-ready pipeline documentation for CLI tools.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Understand the job-to-be-done, the ideal user, and the boundaries of the CLI Pipe and Redirection Behavior Prompt.

This prompt is designed for CLI tool maintainers and platform engineers who need to document how a command behaves as a composable unit inside Unix pipelines. The core job-to-be-done is producing per-command documentation that explains stdin/stdout contracts, exit code propagation, signal handling, buffering behavior, and common pipeline patterns. It is not a general-purpose command reference generator. You should use this prompt when you already have flag documentation, subcommand trees, and basic usage examples, but you need to explain to users how the command composes with other tools, what happens when input is empty or a pipe breaks, and how to handle errors in a pipeline.

The ideal user is an engineer who understands process composition and needs to communicate data flow contracts to other developers. The prompt requires specific inputs: the command's help text or source annotations, known exit codes, and any existing documentation about input/output formats. It produces structured documentation covering the command's behavior as a pipeline component, including whether it reads from stdin by default or requires explicit flags, whether it buffers output or streams line-by-line, how it propagates or masks child process exit codes, and which signals it handles or forwards. The output should include concrete pipeline examples that demonstrate composition with common tools like grep, jq, xargs, and awk.

Do not use this prompt for generating initial flag references, subcommand trees, or installation guides. Those are separate documentation concerns covered by other prompts in the CLI documentation family. This prompt also assumes the command's basic behavior is stable and documented; it is not suitable for reverse-engineering undocumented binaries or for commands that do not participate in standard Unix pipelines. Before using this prompt, ensure you have validated the command's actual pipeline behavior through testing, as the prompt's output must be verified against real execution traces. If the command exhibits non-standard buffering, requires a TTY, or has complex signal handling, you should supplement the prompt's output with empirical test results.

PRACTICAL GUARDRAILS

Use Case Fit

Where the CLI Pipe and Redirection Behavior Prompt works and where it introduces risk. Use these cards to decide if this prompt fits your current documentation task.

01

Good Fit: Documenting Composability Contracts

Use when: you need to document how a command reads from stdin, writes to stdout/stderr, and propagates exit codes. The prompt excels at extracting the explicit and implicit contracts that allow commands to compose reliably in pipelines. Guardrail: Always validate the generated documentation by running the documented pipeline examples in a test harness.

02

Bad Fit: Reverse-Engineering Undocumented Binaries

Avoid when: the CLI tool is a black-box binary with no source access, no --help output, and no existing documentation. The prompt cannot reliably infer buffering behavior, signal handling, or TTY detection logic from black-box observation alone. Guardrail: Pair with runtime tracing tools like strace or dtrace to capture actual system calls before prompting.

03

Required Inputs: Source Code and Help Text

What to watch: The prompt produces shallow or incorrect documentation when given only command names without implementation context. Guardrail: Provide the command's source code (or decompiled logic), full --help output, and any existing man pages. The prompt needs to see how stdin is consumed, how signals are trapped, and how exit codes are set.

04

Operational Risk: Stale Pipeline Examples

Risk: Generated pipeline examples may reference deprecated flags, removed subcommands, or changed output formats, leading to broken documentation on the next release. Guardrail: Integrate the generated examples into your CI/CD pipeline. Run each documented pipeline against the current binary and fail the build if any example produces an unexpected exit code or output.

05

Operational Risk: Undocumented Buffering Side Effects

Risk: The prompt may miss subtle buffering behavior (line vs. block buffering) that changes how commands behave in pipes versus interactive terminals. This leads to documentation that works in a terminal but deadlocks in a script. Guardrail: Explicitly prompt for buffering mode documentation and test each pipeline example with both stdbuf and unbuffered variants.

06

Good Fit: Onboarding Engineers to Pipeline Design

Use when: you need to teach other engineers how your CLI tools compose. The prompt generates composability notes that explain why a command works in a pipeline, not just that it does. Guardrail: Include counterexamples of broken pipelines in the documentation to help users recognize and debug common composition failures.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for generating per-command pipeline documentation, including stdin/stdout contracts, exit code propagation, and composability notes.

This prompt template generates structured documentation for how a specific CLI command behaves in pipelines. It forces the model to reason about stdin/stdout contracts, buffering behavior, exit code propagation, and signal handling—details that are often omitted from standard command references but are critical for engineers composing reliable shell pipelines. Copy the template below, replace the square-bracket placeholders with your command's specifics, and run it against your chosen model.

text
You are a technical writer documenting CLI pipeline behavior for the command [COMMAND_NAME] version [VERSION].

Your task is to produce a Pipeline Behavior Reference section that explains how this command interacts with pipes, redirects, and process composition.

## Required Inputs
- Command help text or source annotations: [HELP_TEXT_OR_SOURCE]
- Known exit codes and their meanings: [EXIT_CODES]
- Output format documentation (if applicable): [OUTPUT_FORMATS]

## Output Schema
Return a JSON object with the following structure:
{
  "command": "string",
  "stdin_contract": {
    "expects_input": "boolean",
    "input_type": "text | binary | json | csv | none",
    "encoding": "string (e.g., UTF-8, raw bytes)",
    "tty_vs_pipe_behavior": "string describing differences between interactive terminal input and piped input",
    "empty_input_behavior": "string describing what happens when stdin is empty or /dev/null",
    "buffering_notes": "string describing line-buffered vs block-buffered vs unbuffered behavior"
  },
  "stdout_contract": {
    "output_type": "text | binary | json | csv | mixed",
    "encoding": "string",
    "tty_vs_pipe_behavior": "string describing differences between terminal output and piped output (e.g., color stripping, formatting changes)",
    "is_reproducible": "boolean (does the same input always produce byte-identical output?)",
    "partial_output_on_failure": "string describing what, if anything, is written to stdout before a non-zero exit"
  },
  "stderr_contract": {
    "contains_diagnostics": "boolean",
    "contains_progress": "boolean",
    "contains_errors_only": "boolean",
    "machine_parseable": "boolean"
  },
  "exit_code_propagation": {
    "exit_codes": [
      {
        "code": "integer",
        "meaning": "string",
        "propagates_from_subprocess": "boolean",
        "recoverable": "boolean"
      }
    ],
    "pipefail_behavior": "string describing behavior under set -o pipefail",
    "signal_handling": {
      "sigpipe": "string describing behavior when downstream pipe closes",
      "sigint": "string describing interrupt behavior",
      "sigterm": "string describing termination behavior"
    }
  },
  "pipeline_patterns": [
    {
      "pattern": "string (a realistic pipeline example)",
      "description": "string explaining what the pattern does",
      "expected_behavior": "string describing expected stdout, stderr, and exit code",
      "caveats": "string listing any gotchas or edge cases"
    }
  ],
  "composability_notes": "string summarizing how this command composes with others, including known incompatibilities"
}

## Constraints
- Only document behavior you can verify from the provided help text or source annotations. If a behavior is undocumented, mark it as "unknown" rather than guessing.
- For each pipeline pattern, ensure the example is syntactically correct and uses realistic file names or inputs.
- Flag any behavior that differs between platforms (Linux, macOS, Windows) if evidence exists in the provided material.
- Do not invent exit codes or signal behaviors not present in the source material.

## Examples
[EXAMPLES]

## Risk Level
[RISK_LEVEL]

Adaptation notes: Replace [COMMAND_NAME] and [VERSION] with the specific command and release version. Populate [HELP_TEXT_OR_SOURCE] with the raw --help output, man page content, or relevant source code annotations. Fill [EXIT_CODES] with a structured list of known exit codes from your exit code documentation prompt. Use [OUTPUT_FORMATS] to describe any structured output modes (JSON, CSV, table). The [EXAMPLES] placeholder should contain 2-3 few-shot examples of correctly filled schemas for similar commands to guide output shape. Set [RISK_LEVEL] to low, medium, or high based on whether incorrect pipeline documentation could cause data loss, silent failures, or production incidents. For high-risk commands, add a human review step before publishing the generated documentation.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the CLI Pipe and Redirection Behavior Prompt. Each placeholder must be populated before the prompt is assembled. Validation notes describe how to verify the input is correct before sending it to the model.

PlaceholderPurposeExampleValidation Notes

[COMMAND_NAME]

The CLI command being documented for pipe and redirection behavior

kubectl get pods

Must match an actual command in the target CLI. Validate by running which [COMMAND_NAME] or checking the binary path.

[COMMAND_VERSION]

The exact version of the CLI tool the documentation describes

v1.28.0

Must match output of [COMMAND_NAME] --version. Reject if version string is empty or does not parse to a semver or date-based version.

[STDIN_CONTRACT]

Description of what the command reads from stdin, including expected format, encoding, and behavior when stdin is empty or closed

Reads newline-delimited JSON from stdin. Expects UTF-8 encoding. Exits with code 1 on empty input.

Validate by piping known-good and known-bad input through the command and comparing exit codes and stderr output to the contract.

[STDOUT_CONTRACT]

Description of what the command writes to stdout, including format, encoding, buffering behavior, and whether output is suitable for piping

Writes JSON array to stdout. Line-buffered when stdout is a pipe, block-buffered when stdout is a file.

Validate by comparing [COMMAND_NAME] | cat output format against [COMMAND_NAME] > file output. Check for truncation or encoding mismatches.

[STDERR_CONTRACT]

Description of what the command writes to stderr, including log levels, progress indicators, and whether stderr is safe to suppress in pipelines

Writes info-level logs to stderr. Progress bar is suppressed when stderr is not a TTY.

Validate by running [COMMAND_NAME] 2>/dev/null and confirming no critical errors are lost. Check TTY detection with [ -t 2 ] equivalent.

[EXIT_CODES]

Map of exit codes to meanings, including which codes indicate pipe-compatible failures vs terminal failures

0: success, 1: input error, 2: partial output written, 141: SIGPIPE received

Validate by triggering each exit code in a pipeline context and confirming the documented code matches actual behavior. Check $? after [COMMAND_NAME] | head -n 1 for SIGPIPE handling.

[SIGNAL_BEHAVIOR]

How the command responds to SIGPIPE, SIGTERM, and SIGINT, including whether it cleans up partial output or exits immediately

Traps SIGPIPE and exits 141 after flushing buffers. SIGTERM triggers graceful shutdown with partial output written.

Validate by sending signals in a pipeline: [COMMAND_NAME] | head -n 1; echo ${PIPESTATUS[0]}. Confirm cleanup behavior with temporary file inspection.

[BUFFERING_MODE]

Whether the command uses line buffering, block buffering, or no buffering, and how that changes between pipe and file output

Line-buffered for stdout when piped. Block-buffered (4KB) when redirected to a file. Stderr is always unbuffered.

Validate by measuring output latency: [COMMAND_NAME] | while read line; do echo $line; done vs [COMMAND_NAME] > file && tail -f file. Check for delayed output.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the CLI pipe and redirection behavior prompt into a documentation generation pipeline with validation, retries, and human review gates.

This prompt is designed to be called programmatically as part of a CLI documentation build step. The typical harness reads a command's --help output, its source annotations, or a structured command spec, then passes that data into the prompt as [COMMAND_SPEC] and [BEHAVIOR_EVIDENCE]. The model returns a structured pipeline behavior document that your system can render into Markdown, man pages, or a web reference. Because pipeline behavior documentation describes how commands compose, the harness must validate that every documented stdin/stdout contract, exit code propagation rule, and buffering note is internally consistent before publication.

Wire the prompt into a documentation pipeline that runs per-command. For each command, assemble the input context from: (1) the command's --help output or a parsed flag schema, (2) any source-level annotations about pipe behavior, signal handling, or TTY detection, and (3) a list of sibling commands that commonly appear in pipelines with this command. Pass these into [COMMAND_SPEC] and [BEHAVIOR_EVIDENCE] respectively. After the model returns its output, run a structured validation step: parse the documented stdin/stdout contracts and check that every claimed exit code appears in the command's actual exit code catalog. Flag any pipeline example that references a flag not present in the command's flag schema. For high-risk commands that modify filesystems or network state, add a human review gate before publication—an engineer should confirm that buffering behavior notes (line-buffered vs. block-buffered) match actual implementation, since incorrect buffering documentation causes the hardest-to-debug pipeline failures.

For retry logic, if the model output fails schema validation (missing required sections like stdin_contract, stdout_contract, pipeline_examples, or buffering_behavior), retry once with the validation errors appended to [CONSTRAINTS]. If the retry also fails, route the command to a manual documentation queue. Log every generation attempt with the command name, model version, validation pass/fail status, and whether human review was required. Avoid shipping pipeline documentation that claims a command "propagates all exit codes" unless you have tested that claim against actual set -o pipefail and PIPESTATUS behavior in your target shells.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the exact fields, types, and validation rules for the pipeline behavior documentation generated by the prompt. Use this contract to parse and validate the model's output before publishing.

Field or ElementType or FormatRequiredValidation Rule

command_name

string

Must match the exact command string from [COMMAND_NAME] input. Non-empty and trimmed.

stdin_contract

object

Must contain 'expected_type' (enum: text, binary, json, null), 'encoding' (string), and 'behavior_when_closed' (enum: exits_gracefully, errors, ignores). Schema check required.

stdout_contract

object

Must contain 'format' (enum: text, json, csv, binary, raw), 'is_tty_aware' (boolean), and 'buffering' (enum: line, block, none). Schema check required.

stderr_behavior

object

Must contain 'outputs_to' (enum: stderr, stdout, both, null) and 'contains_diagnostics' (boolean). If null, 'contains_diagnostics' must be false.

exit_code_propagation

object

Must contain 'on_success' (integer), 'on_pipe_failure' (integer), and 'uses_pipefail' (boolean). Integer fields must be in range 0-255.

signal_handling

array

Each item must be an object with 'signal' (string, e.g., SIGPIPE, SIGTERM) and 'behavior' (string). Array must not be empty; include at least SIGPIPE.

common_pipeline_patterns

array

Each item must be an object with 'description' (string), 'command_sequence' (string), and 'expected_outcome' (string). Array must contain at least 2 patterns. 'command_sequence' must be a valid shell pipeline string.

composability_notes

string

Must be a non-empty string summarizing idempotency, statefulness, and side effects when used in pipelines. Max 500 characters.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when documenting CLI pipe and redirection behavior, and how to guard against it.

01

TTY vs. Pipe Behavior Confusion

What to watch: The prompt describes interactive terminal behavior (color, prompts, progress bars) that disappears or breaks when stdout is redirected or piped. The model may assume a TTY context. Guardrail: Explicitly require separate documentation sections for 'Interactive Terminal (TTY)' and 'Pipe/Redirect (Non-TTY)' behavior. Test generated examples with | cat or > /dev/null to verify output format changes.

02

Buffering-Induced Pipeline Deadlocks

What to watch: The model ignores stdio buffering semantics (line vs. full buffering), producing pipeline examples that deadlock or exhibit extreme latency. This is common with stdbuf, unbuffer, or complex multi-stage pipes. Guardrail: Add a constraint requiring explicit notes on buffering behavior for each command. Validate pipeline examples by checking for standard buffering workarounds like stdbuf -oL or --line-buffered flags where applicable.

03

Incorrect Exit Code Propagation

What to watch: The documentation implies standard exit code semantics (e.g., last command wins) without accounting for set -o pipefail, PIPESTATUS, or commands that ignore SIGPIPE. This leads to incorrect error-handling advice in scripts. Guardrail: Require a dedicated 'Exit Code and Pipeline Status' section. Test all documented pipeline examples in a shell with pipefail enabled and disabled to verify the documented exit code behavior matches reality.

04

Stdin Exhaustion and Multi-Command Reads

What to watch: The prompt generates a pipeline where multiple commands read from stdin, but the first command consumes the entire stream, leaving subsequent commands with empty input. Guardrail: Add a rule that any pipeline with multiple stdin consumers must document the input flow explicitly. Validate by checking if the documented pattern uses process substitution <(cmd) or explicit file descriptors to avoid stdin contention.

05

Binary vs. Text Stream Corruption

What to watch: The documentation assumes text streams and recommends tools like grep or sed that corrupt binary data (e.g., adding newlines, dropping null bytes) when used in pipelines with binary payloads. Guardrail: Require explicit labeling of each command's input/output encoding contract (text, binary, UTF-8, etc.). Flag any example that pipes binary data through a text-oriented command without a safe intermediary like xxd or base64.

06

SIGPIPE and Broken Pipe Handling Omission

What to watch: The model documents a pipeline where an early command exits, but fails to mention that downstream commands will receive SIGPIPE or write errors. This leads to confusing 'broken pipe' messages in production scripts. Guardrail: Mandate a 'Signal Handling' note for any pipeline exceeding two commands. Validate by running the documented pipeline with an intentionally early-exiting head command (e.g., head -n 1) and checking if the documentation warns about the resulting SIGPIPE.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality and correctness of generated CLI pipe and redirection documentation before shipping it to users.

CriterionPass StandardFailure SignalTest Method

Stdin/Stdout Contract Accuracy

Documented stdin expectations and stdout format match actual command behavior for both pipe and TTY modes

Example pipeline fails because documented input format is wrong or output format differs from actual

Execute documented pipeline examples in a test harness and diff actual output against documented output

Exit Code Propagation Coverage

All exit codes documented with pipe-specific behavior (e.g., set -o pipefail, PIPESTATUS) and SIGPIPE handling

Documentation omits exit code 141 for broken pipe or fails to mention PIPESTATUS for multi-command pipelines

Run pipeline scenarios that trigger each exit code and verify documentation matches observed behavior

Buffering Behavior Description

Line-buffered vs block-buffered behavior is correctly documented for pipe, redirect, and TTY modes

Documentation claims line-buffered output but actual behavior is block-buffered, causing pipeline stalls

Use stdbuf or unbuffer to test buffering mode and compare against documented claims

Pipeline Example Correctness

Every documented pipeline example executes successfully with the documented exit code and output

Example fails due to missing flag, wrong order, or incompatible command versions

Copy-paste each example into a clean shell environment and verify exit code and output match

Edge Case Coverage

Documentation addresses empty input, binary data, closed pipes, and large input scenarios

No mention of behavior when stdin is /dev/null or when pipe reader exits early

Test each edge case explicitly and check if documentation describes expected behavior

Signal Handling Documentation

SIGPIPE, SIGINT, and SIGTERM behavior during pipeline execution is correctly described

Documentation claims SIGINT is caught but actual command exits immediately without cleanup

Send signals to pipeline processes and verify documented signal handling matches observed behavior

Redirection Operator Accuracy

All redirection operators (>, >>, 2>, &>, <, <<<) are documented with correct overwrite/append semantics

Documentation says > appends when it actually overwrites, or omits noclobber behavior

Test each redirection operator with set -o noclobber and verify documented semantics

Composability Notes Completeness

Documentation includes known incompatibilities, ordering constraints, and recommended pipeline patterns

User builds a pipeline that silently corrupts data because an undocumented ordering constraint was violated

Review composability notes against issue tracker for reported pipeline bugs and verify coverage

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a single command's --help output. Use a frontier model with minimal constraints. Focus on getting the pipe behavior description right for one command before scaling.

code
Analyze the following CLI help text and describe how [COMMAND] behaves in pipelines:

- What does it read from stdin? Under what conditions?
- What does it write to stdout vs stderr?
- What exit codes does it produce on pipe failure?
- Does behavior differ between TTY and non-TTY (pipe) mode?
- How does it handle SIGPIPE?

Help text:
[HELP_TEXT]

Watch for

  • Missing edge cases: empty stdin, binary input, closed pipe mid-stream
  • Overconfident claims about behavior not evident in help text alone
  • No distinction between documented and inferred behavior
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.