Running a command alongside a Codex prompt keeps responses tied to real output instead of assumptions, which is useful for listing files, summarizing logs, or extracting details without manual transcription.

The codex exec subcommand executes the supplied command in the configured sandbox and captures its stdout and stderr for the model to use while generating the response. Progress streams to stderr while the final assistant message prints to stdout, so piping stdout keeps only the response.

Keep commands safe and deterministic because changing state or producing noisy output makes results harder to trust. Avoid printing secrets into command output, and trim large outputs with narrower paths, filters, or line limits so only relevant context is provided.

Steps to run Codex exec with a command:

  1. Run codex exec with a prompt that includes the command to execute.
    $ codex -a on-request exec -C /home/user/projects/exec-demo "Run rg --files -g '*.md' and return only the filenames."
    README.md
    docs/usage.md

    The quoted string after exec is the prompt; include the command you want Codex to run so it can execute it inside the sandboxed workspace. rg (ripgrep) lists candidate files with --files and filters with --glob (-g).

    Destructive commands like rm, git reset, or git clean can delete files and change later command output.

  2. Quote globs and other shell-sensitive patterns inside the command you ask Codex to run.
    $ codex -a on-request exec -C /home/user/projects/exec-demo "Run rg --line-number 'TODO' -g '*.md' and return file:line for each match."
    README.md:3
    docs/usage.md:3

    Keep glob patterns like '*.md' quoted so the shell passes them to the tool unchanged.

  3. Reduce command output by limiting scope with command options or paths.
    $ codex -a on-request exec -C /home/user/projects/exec-demo "Summarize the key errors from the last 200 lines of the build log in 3 bullet points. Run: tail -n 200 build.log"
    - Tests failed: 2 failures due to missing fixture files.
    - Linter error: E501 line too long in `src/api/client.py`.
    - Build aborted after 3 errors.

    When a pipeline is required for trimming, run it through a shell, for example: bash -lc 'tail -n 200 build.log | rg "ERROR|WARN" | head -n 50'.

  4. Verify command output is being used by requesting an exact extraction from a self-contained command.
    $ codex -a on-request exec -C /home/user/projects/exec-demo "Reply with only the last line of the command output. Run: printf '%s\n' alpha beta gamma"
    gamma