Saving cURL Responses to Files
One of the most common use cases for cURL is saving the response from a request to a file. This can be useful for a variety of purposes, such as downloading files, caching API responses, or logging server responses.
Saving Responses Using the -o and -O Flags
The simplest way to save a cURL response to a file is by using the -o
or -O
flags:
## Save the response to a file named "example.html"
curl -o example.html https://www.example.com
## Save the response using the remote file name
curl -O https://www.example.com/file.zip
The -o
flag allows you to specify the name of the output file, while the -O
flag will use the remote file name.
Saving Responses to Multiple Files
If you need to save multiple responses to different files, you can use the -o
flag multiple times:
curl -o file1.html https://example.com/page1
curl -o file2.html https://example.com/page2
curl -o file3.html https://example.com/page3
This will save the responses from the three URLs to file1.html
, file2.html
, and file3.html
, respectively.
Saving Responses with Automatic Naming
If you don't want to specify the output file name manually, you can use the --remote-name
or --remote-header-name
flags to automatically name the output file:
## Use the remote file name
curl --remote-name https://example.com/file.zip
## Use the Content-Disposition header to determine the file name
curl --remote-header-name https://example.com/download
The --remote-name
flag will use the last part of the URL as the output file name, while the --remote-header-name
flag will use the file name specified in the Content-Disposition
header.
Saving Responses with Conditional Requests
In some cases, you may want to only download a file if it has been updated since the last time you downloaded it. You can use the If-Modified-Since
header to achieve this:
curl -z example.html -o example.html https://example.com/file.html
This will only download the file if it has been modified since the last time the example.html
file was downloaded.
By understanding these cURL file saving techniques, you can effectively manage and automate the process of downloading and storing data from various sources in your Linux environment.