How to 'Catch' the Downloaded Filename using wget and cURL Commands?

Abstract: Extract the original filename from HTTP Content-Disposition headers using wget or cURL for reliable file naming in automation scripts.

Created: 2026-08-12 by
To retrieve the original filename from a download URL using wget or cURL, you must rely on HTTP headers rather than parsing the URL itself. The most reliable method is extracting the value of the Content-Disposition header, which explicitly specifies the name the server intends for the file. If this header is absent, you can fall back to deriving the name from the last segment of the URL path after removing query parameters.

Understanding Content-Disposition Headers

When a web server sends a file, it often includes metadata in the response headers that tells the client how to handle the content. One of these headers is Content-Disposition. This header can take two primary forms: inline, suggesting the browser should display the content directly, and attachment, which prompts the user to save the file. When used with attachment, it almost always contains a filename parameter that defines the exact name to be used when saving. For example, a typical header might look like this: Content-Disposition: attachment; filename="report_2023.pdf" This mechanism is robust because it allows the server to rename files dynamically without changing the URL structure. For instance, multiple users downloading the same report might receive different filenames based on their session data, yet the URL remains constant. Therefore, relying on the URL path alone is insufficient for accurate automation.

Extracting Filename with cURL

The cURL utility provides powerful options for inspecting and manipulating HTTP responses. To catch the filename, you need to request only the headers without downloading the entire body of the file. This is achieved using the -I (or --head) flag. By combining this with -s for silent mode, you prevent progress meters from cluttering your output, making it easier to parse programmatically. You can pipe the output through grep to find the specific line containing the disposition information. However, simply grepping for "filename" might yield false positives if other headers contain similar text. A more precise approach involves using regular expressions to extract the value between quotes or equals signs. Here is a robust shell snippet to extract the filename using cURL:
url="https://example.com/download.php?id=123"
filename=$(curl -sI "$url" | grep -i 'content-disposition' | sed 's/.*filename[^=]*=\(.*\)/\1/' | sed 's/^[""\']//;s/[""\']$//')
echo "Filename: $filename"
In this command, sed performs two critical steps. First, it isolates the part of the string after filename=. Second, it strips any surrounding quotation marks that are commonly present in MIME headers. This ensures that the variable $filename contains a clean string ready for use in subsequent script commands.

Extracting Filename with wget

While wget is excellent for downloading files, it does not have a direct single-command equivalent to cURL's -I flag for just fetching headers in all versions. However, you can achieve similar results by running wget with the --server-response option (often abbreviated as -S). This prints the remote server's response to standard error. To capture this output into a variable, you must redirect standard error to standard output using 2>&1. Then, you can process the stream exactly as you would with cURL.
url="https://example.com/download.php?id=456"
headers=$(wget --server-response -O /dev/null "$url" 2>&1)
filename=$(echo "$headers" | grep -i 'content-disposition' | sed 's/.*filename[^=]*=\(.*\)/\1/' | sed 's/^[""\']//;s/[""\']$//')
echo "Filename: $filename"
Note that we use -O /dev/null to ensure no actual file data is written to disk during this inspection phase. This makes the operation fast and efficient. It is important to note that wget behavior can vary slightly across versions, so testing this snippet in your specific environment is recommended.

Fallback Strategies

Not all servers provide the Content-Disposition header correctly. Some may omit it entirely, while others might use non-standard formatting. In such cases, you need a fallback strategy. The most common alternative is to parse the URL itself. You can extract the last component of the URL path, assuming it represents the filename. However, URLs often include query strings (e.g., ?v=1.2) or trailing slashes that complicate this extraction. You should remove query parameters first using tools like awk or sed, then extract the basename. If both the header and the URL parsing fail, consider checking the Content-Type header to infer the file extension, although this will not give you the base name. For more advanced scenarios involving complex redirection chains, you might need to follow redirects manually to see the final destination URL before applying these extraction techniques. This is particularly relevant when dealing with services that use short links or API endpoints that redirect to cloud storage providers like AWS S3 or Azure Blob Storage.

Handling Special Characters and Spaces

Filenames often contain spaces, special characters, or even unicode characters. When capturing these values in a shell script, proper quoting is essential to prevent word splitting or globbing issues. Always enclose your variables in double quotes when passing them to other commands. Additionally, some servers encode filenames in the header using percent-encoding (URL encoding). For example, a space might appear as %20. If your downstream processes require a human-readable name, you may need to decode these sequences. Tools like printf or specialized utilities like python3 -c can help decode these strings if necessary. It is also worth noting that some servers provide both a filename* parameter (RFC 5987 encoded) and a legacy filename parameter. Modern browsers prefer filename*, but older scripts might only check for filename. Ensure your parsing logic checks for both variants to maximize compatibility.

Frequently Asked Questions

What if the Content-Disposition header is missing?

If the header is missing, you must parse the URL path as a fallback. Extract the last segment of the URL after the final slash, ignoring any query parameters starting with a question mark. This method is less reliable because servers do not guarantee the URL path matches the desired filename.

How do I handle filenames with spaces in bash scripts?

Always wrap your extracted filename variable in double quotes whenever you use it in commands. For example, use "$filename" instead of $filename. This prevents the shell from splitting the string at spaces and treating each part as a separate argument.

Can I use wget to download and rename automatically?

Yes, wget has an -O option that allows you to specify the output filename directly. However, this requires you to know the filename beforehand or extract it separately first. You cannot combine the download and automatic renaming into a single atomic step without prior knowledge of the target name.

Why does my regex fail on some servers?

Regex failures usually occur due to variations in header formatting. Some servers put the filename in quotes, others do not. Some use = while others use = followed by a space. Make sure your sed or grep patterns account for optional whitespace and quote characters around the filename value.

Is there a difference between curl -I and curl -L?

-I fetches only headers, while -L follows redirects. If the download URL redirects to another location that sets the Content-Disposition header, you must use -L combined with -I (i.e., curl -sIL) to see the headers of the final destination. Without following redirects, you might miss the correct filename provided by the final server.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More