Saving the last Codex response to a file is useful when a script, CI job, or follow-up command needs the final assistant reply without parsing terminal progress text.
In codex exec, the final assistant message is still printed to stdout while progress is streamed separately. The --output-last-message flag writes that same final message to a file so you can reuse it later.
Use --json when another program needs every event from the run, or --output-schema when the saved response must follow a JSON contract. Choose a writable file path in an existing directory because Codex does not create missing parent directories for --output-last-message, and a later run replaces the file contents instead of appending to them.
Related: How to enable JSON output in Codex
Related: How to use output schema in Codex
Steps to save the last Codex response to a file:
- Run codex exec with --output-last-message and the file path you want to keep.
$ codex exec --output-last-message codex-response.txt "Reply with exactly: OK." OK.
The final reply is still printed to stdout while the same text is written to codex-response.txt. Add >/dev/null when only the file output is needed. Related: How to fix Codex trusted directory error
- Open the saved file and confirm it contains the final assistant message.
$ cat codex-response.txt OK.
- Reuse the same destination path when you want the newest final reply to replace the older one.
$ codex exec --output-last-message codex-response.txt "Reply with exactly: Updated OK." Updated OK.
--output-last-message overwrites the destination file when it already exists.
- Read the file again and confirm it now contains the latest reply.
$ cat codex-response.txt Updated 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.
