Saving the last Codex assistant response to a file makes output easy to reuse for scripts, reviews, and follow-up prompts without copy-pasting from the terminal.

The Codex CLI can write the final assistant message to disk using --output-last-message (or -o) while still emitting the same response to stdout. This is ideal for automation that needs a clean file output without switching to JSONL.

The destination file is overwritten when it already exists, so choose a predictable path and apply restrictive permissions when responses may contain secrets. Some environments restrict output paths to trusted locations, so storing under the home directory avoids common policy errors.

Steps to save the last Codex response to a file:

  1. Create a destination directory for saved Codex responses.
    $ mkdir -p ~/codex-responses
  2. Run Codex with --output-last-message set to the desired file path.
    $ codex exec -o ~/codex-responses/last-response.txt -C /home/user/projects/example-repo "Return OK."
    OK

    The destination file is overwritten when it already exists.

    Stdout output can be suppressed with shell redirection when only the file output is needed, for example >/dev/null.

  3. Restrict the saved response file permissions when the output may contain sensitive data.
    $ chmod 600 ~/codex-responses/last-response.txt

    Owner-only permissions reduce accidental exposure when the response includes credentials, tokens, or internal data.

  4. Confirm the file permissions are restricted.
    $ ls -l ~/codex-responses/last-response.txt
    -rw-------  1 user  user  2 Jan 19 11:42 /home/user/codex-responses/last-response.txt
  5. Verify the file contains the expected response text.
    $ cat ~/codex-responses/last-response.txt
    OK