Curl Option to Write Headers to a Text File

This article explains how to use the curl command-line tool to save received HTTP response headers directly to a specific text file. It identifies the exact command-line option required and provides practical examples of how to implement it in your terminal.

The curl option used to write received headers to a specified text file is -D (or the long-form equivalent, --dump-header).

When you use this option, curl intercepts the protocol headers from the server’s response and writes them into the file path you define. This is particularly useful for debugging API responses, inspecting cookies, or automating scripts that need to parse HTTP status codes and headers without mixing them with the response body.

Basic Syntax

To use this option, append -D followed by the desired text file name to your curl command:

curl -D headers.txt https://example.com

In this example, curl fetches the content of https://example.com, outputs the response body to your terminal (standard output), and saves only the HTTP headers to a file named headers.txt.

Saving Headers and Redirecting the Body

If you want to save the HTTP headers to one file and the actual HTML or JSON response body to another file, you can combine -D with the -o (output) option:

curl -D headers.txt -o response_body.html https://example.com

After running this command: * headers.txt will contain the HTTP response headers (such as Content-Type, Date, Server, etc.). * response_body.html will contain the main payload of the website.

Appending Headers for Redirects

If the URL you are requesting redirects to another page, curl can follow the redirects using the -L option. By default, the -D option will overwrite the text file with the headers of the final destination page. If you want to record the headers of every redirect hop along the way, use a single hyphen - as the filename to send them to stdout, or rely on curl’s default behavior of appending subsequent headers to the same file during a single execution.