Commands.page Logo

Ubuntu Curl Download Rename Based on Server Response Header

This article provides a direct guide on how to download files in Ubuntu while automatically renaming them according to the server’s response headers. It identifies the specific command-line tools capable of this task, focusing on the necessary flags to ensure the local filename matches the remote Content-Disposition header. Readers will learn the exact syntax required for curl and wget to achieve this functionality safely and efficiently.

Using Curl with Remote Header Names

The primary command for this operation is curl. To download a file and rename it based on the server’s response header, you must use the -J flag combined with the -O flag. The -O flag saves the file using the remote file name, and -J tells curl to use the filename provided in the Content-Disposition header instead of the URL path.

curl -JO [URL]

Replace [URL] with the specific address of the file you want to download. When executed, curl queries the server, reads the response header, and saves the file using the name specified by the server. This is particularly useful when download links are dynamic or obscured.

Using Wget with Content Disposition

Users who prefer wget can achieve similar results using the --content-disposition flag. This option instructs wget to honor the Content-Disposition header if it is present in the server’s response.

wget --content-disposition [URL]

This command ensures the saved file matches the server’s suggested filename rather than defaulting to the name found in the URL string. Ensure your version of wget supports this flag, as it is standard in most modern Ubuntu repositories.

Security Best Practices

When using these commands, exercise caution regarding file overwrites. Since the server determines the filename, a malicious source could specify a name that conflicts with existing scripts or critical files in your directory. Always run these commands in a dedicated download folder and verify the resulting filename before executing any downloaded content.