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.
Related: How to enable JSON output in Codex exec
Related: How to use a Codex output schema
Steps to save the last Codex response to a file:
- Create a destination directory for saved Codex responses.
$ mkdir -p ~/codex-responses
- 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.
- 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.
- 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
- Verify the file contains the expected response text.
$ cat ~/codex-responses/last-response.txt OK
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.
