Website Vidya
Web ServerStep-by-Step Guide

wget Command in Linux: Download Files, Mirrors, and Background Transfers

Learn wget command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
10 min read
PDF Cheat Sheet
wget Command in Linux: Download Files, Mirrors, and Background Transfers
AI Executive SummaryWebsiteVidya AI

10 min read

Learn wget command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What wget Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

The wget command in linux is one of the most reliable and widely deployed command-line utilities for retrieving files across computer networks. Created by Hrvoje Nikšić in 1996 as part of the GNU Project, wget was designed from its inception to function non-interactively, making it the ideal tool for automated scripts, cron jobs, and unattended server provisioning workflows.

In enterprise environments, file downloads must frequently withstand network latency, dropped TCP connections, and multi-gigabyte payloads (such as database snapshots, operating system ISOs, and container layers). Unlike interactive web browsers, wget detects interrupted connections, waits, re-establishes network sockets, and resumes downloading from the exact byte offset where the stream was severed without corrupting the file.

Beyond basic file downloads, wget incorporates a recursive web crawler engine capable of traversing HTML links, converting relative URLs for local browsing, following directory structures over FTP, and mirroring entire documentation websites for offline accessibility.

Advertisement
wget Command in Linux: Download Files, Mirrors, and Background Transfers — syntax, flags, and practical terminal workflow diagram
wget Command in Linux: Download Files, Mirrors, and Background Transfers — command syntax, key options, and production workflow reference.

What wget Does and When to Use It

At the architectural level, wget implements the HTTP/1.1 and FTP network protocols over TCP sockets. When downloading over HTTPS, it interfaces with TLS libraries (such as GnuTLS or OpenSSL) to validate server X.509 certificate chains against the operating system's trust store (/etc/ssl/certs). For resuming downloads (-c), wget inspects the size of the existing local file and includes an HTTP Range header (e.g., Range: bytes=1048576-) in the request, prompting the web server to return a 206 Partial Content response.

Wget's recursive crawling engine parses HTML, XHTML, and CSS documents as they are retrieved in memory. It constructs an internal directed graph of hyperlinks, tracking visited URLs in a hash table to prevent infinite loops. When mirroring (-m), it evaluates timestamp headers (If-Modified-Since) to download only updated assets, respecting robots.txt exclusion standards by default.

At the operating system level, wget interacts with the Linux kernel networking stack through netlink sockets (AF_NETLINK), raw packet sockets, or standard POSIX resolver APIs. When running wget in cloud instances or Kubernetes worker nodes, combining flags such as -O FILE, -P DIR, -c, -b lets you bypass slow reverse DNS lookups and inspect numeric IPv4/IPv6 addresses and socket states directly.

Availability and Installation Across Linux Distributions

The wget utility is packaged in wget across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether wget is installed and inspect which binary path and version your shell resolves:

type -a wget
wget --version 2>/dev/null || man -f wget

# Illustrative output (reviewed against documentation)
wget is /usr/bin/wget
wget (wget)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y wget

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y wget

# Arch Linux
sudo pacman -S --noconfirm wget

# Alpine Linux
sudo apk add --no-cache wget

Command Syntax, Arguments, and Exit Status Codes

wget [OPTION]... [URL]...

The basic syntax is: wget [OPTION]... [URL]... You can provide a single URL or multiple space-separated URLs on the command line. If invoked with no options, wget downloads the resource into the current working directory, retaining the filename specified in the URL.

Essential command options control file naming (-O filename, -P /path/to/dir), transfer resilience (-c to resume, -t tries to set retry attempts), background execution (-b with -o logfile), recursive crawling (-r, -l depth, -m for mirroring), and network throttling (--limit-rate=1m).

  • 0 — Successful execution; all requested files were downloaded completely.
  • 1 — Generic operational error code.
  • 2 — Parse error; invalid command-line option syntax.
  • 3 — File I/O error; disk full, permission denied, or unable to create local destination file.
  • 4 — Network failure; connection timed out, DNS lookup failed, or connection refused.
  • 5 — SSL/TLS verification failure; expired or untrusted server certificate.
  • 8 — Server returned an HTTP error response (such as 404 Not Found or 500 Internal Server Error).

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-O FILE--output-document=FILEWrites all downloaded content to a single local file named FILE, concatenating multiple URLs.
-P DIR--directory-prefix=DIRSaves all downloaded files into the specified directory path DIR without renaming.
-c--continueResumes an interrupted or partially downloaded file using HTTP Range headers.
-b--backgroundForks the download process immediately into the background, redirecting output to a log file.
-r--recursiveTurns on recursive web crawling, following HTML links to download linked files.
-m--mirrorEnables mirroring mode (equivalent to -r -N -l inf --no-remove-listing for site backups).
--limit-rate=RATE--limit-rate=RATELimits download bandwidth consumption to RATE (e.g., 500k, 2m) to prevent network congestion.
-q--quietRuns in quiet mode, suppressing progress bars and diagnostic output.
-i FILE--input-file=FILEReads a list of URLs to download sequentially from a local or remote text file FILE.

When downloading large files over unreliable internet connections, combining -c (continue), --tries=0 (infinite retries), and --retry-connrefused creates an indestructible download pipeline that automatically recovers from transient network drops and server restarts.

Advertisement

For creating offline website mirrors, the standard flag combination is wget -m -k -p -E -np https://example.com/docs/. Here, -m enables mirroring, -k converts remote links to local relative links, -p downloads page prerequisites (images, CSS, JS), -E adjusts extensions to .html, and -np prevents ascending into parent directories.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Download a Single File to the Current Working Directory

Download a remote software release archive, displaying a live progress bar and transfer speed.

wget https://example.com/files/release-v2.4.tar.gz

# Illustrative output (reviewed against documentation)
--2026-10-22 21:00:01--  https://example.com/files/release-v2.4.tar.gz
Resolving example.com (example.com)... 93.184.216.34
Connecting to example.com (example.com)|93.184.216.34|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 45210984 (43M) [application/gzip]
Saving to: ‘release-v2.4.tar.gz’

release-v2.4.tar.gz 100%[===================>]  43.12M  12.4MB/s    in 3.5s    

2026-10-22 21:00:05 (12.4 MB/s) - ‘release-v2.4.tar.gz’ saved [45210984/45210984]

Wget resolves the domain, connects via TLS, verifies the 200 OK response, and streams the 43MB file directly to disk.

2. Save Download with a Custom Filename or Directory

Save a remote file under a custom local filename or redirect the output into a specific directory.

wget -O /tmp/custom_name.tar.gz https://example.com/files/release-v2.4.tar.gz

# Illustrative output (reviewed against documentation)
Saving to: ‘/tmp/custom_name.tar.gz’
/tmp/custom_name.tar.gz 100%[===================>]  43.12M  14.2MB/s    in 3.0s

The -O option overrides the remote URL filename, saving the stream directly to /tmp/custom_name.tar.gz.

3. Resume an Interrupted Large File Download

Continue downloading a multi-gigabyte file that was severed prematurely without starting over from byte zero.

wget -c https://example.com/isos/ubuntu-server.iso

# Illustrative output (reviewed against documentation)
--2026-10-22 21:01:00--  https://example.com/isos/ubuntu-server.iso
HTTP request sent, awaiting response... 206 Partial Content
Length: 2147483648 (2.0G), 1073741824 (1.0G) remaining [application/octet-stream]
Saving to: ‘ubuntu-server.iso’

ubuntu-server.iso    100%[++++++=============>]   2.00G  18.5MB/s    in 58s    

2026-10-22 21:01:58 (18.5 MB/s) - ‘ubuntu-server.iso’ saved [2147483648/2147483648]

The -c flag sends an HTTP Range header. The server responds with 206 Partial Content and streams only the remaining 1.0GB.

4. Download in the Background and Log Output to File

Fork long-running downloads into the background so you can safely log out of your SSH session.

wget -b -o /tmp/wget_download.log https://example.com/backups/database_dump.sql.gz

# Illustrative output (reviewed against documentation)
Continuing in background, pid 18450.
Output will be written to ‘/tmp/wget_download.log’.

The -b option detaches the process. Progress is recorded in /tmp/wget_download.log, monitored with tail -f.

5. Limit Download Bandwidth Speed

Throttle transfer rate to prevent saturating shared office or production network bandwidth.

wget --limit-rate=2m https://example.com/large_dataset.zip

# Illustrative output (reviewed against documentation)
large_dataset.zip     35%[=======>            ]  70.00M  2.00MB/s    eta 65s

Wget caps throughput at 2 Megabytes per second (--limit-rate=2m), preserving network capacity for other services.

6. Download Multiple URLs from a Text File

Batch download hundreds of files listed line-by-line in an input text file.

wget -i download_urls.txt -P /data/downloads/

# Illustrative output (reviewed against documentation)
Loading ‘download_urls.txt’...
--2026-10-22 21:05:01--  https://example.com/file1.pdf
Saving to: ‘/data/downloads/file1.pdf’
--2026-10-22 21:05:03--  https://example.com/file2.pdf
Saving to: ‘/data/downloads/file2.pdf’
FINISHED --2026-10-22 21:05:05--

The -i flag reads URLs sequentially from download_urls.txt, saving all items into /data/downloads/.

Real-World Workflows, Pipelines, and Shell Automation

Offline Website Documentation Mirroring Pipeline

Create a complete, self-contained offline mirror of an online technical documentation site with all assets and converted links for offline browsing.

#!/usr/bin/env bash
set -euo pipefail

DOCS_URL="https://example.com/docs/"
MIRROR_DIR="/srv/offline_docs"

mkdir -p "${MIRROR_DIR}"
cd "${MIRROR_DIR}"

echo "=== Starting Offline Documentation Mirror of ${DOCS_URL} ==="
wget \
  --mirror \
  --convert-links \
  --adjust-extension \
  --page-requisites \
  --no-parent \
  --no-verbose \
  --show-progress \
  --wait=1 \
  --random-wait \
  "${DOCS_URL}"

echo "Mirroring complete. Documents ready in ${MIRROR_DIR}."

# Illustrative output (reviewed against documentation)
=== Starting Offline Documentation Mirror of https://example.com/docs/ ===
2026-10-22 21:10:01 URL: https://example.com/docs/ [12450/12450] -> "example.com/docs/index.html" [1]
2026-10-22 21:10:03 URL: https://example.com/docs/setup/ [18200/18200] -> "example.com/docs/setup.html" [1]
2026-10-22 21:10:05 URL: https://example.com/docs/style.css [4510/4510] -> "example.com/docs/style.css" [1]
Mirroring complete. Documents ready in /srv/offline_docs.

This production pipeline downloads all linked documentation pages, stylesheets, and images while rewriting links locally and respecting rate limits with --wait=1.

Automated Software Release Ingestion and Checksum Validation

Download a production binary package and its corresponding SHA256 checksum, verify file integrity, and abort if tampering is detected.

#!/usr/bin/env bash
set -euo pipefail

RELEASE_URL="https://example.com/releases/app-v1.0.tar.gz"
CHECKSUM_URL="https://example.com/releases/app-v1.0.tar.gz.sha256"
TARGET_DIR="/tmp/release_staging"

mkdir -p "${TARGET_DIR}"
cd "${TARGET_DIR}"

echo "=== Downloading Release Package and Checksum ==="
wget -q -c "${RELEASE_URL}"
wget -q -c "${CHECKSUM_URL}"

echo "=== Verifying SHA256 Cryptographic Checksum ==="
if sha256sum -c "app-v1.0.tar.gz.sha256"; then
  echo "INTEGRITY VERIFIED: Package is authentic and uncorrupted."
else
  echo "SECURITY ALERT: Checksum mismatch! Deleting corrupted archive."
  rm -f "app-v1.0.tar.gz"
  exit 1
fi

# Illustrative output (reviewed against documentation)
=== Downloading Release Package and Checksum ===
=== Verifying SHA256 Cryptographic Checksum ===
app-v1.0.tar.gz: OK
INTEGRITY VERIFIED: Package is authentic and uncorrupted.

This workflow ensures automated deployment pipelines never execute corrupt or truncated downloads by pairing wget -c with automated sha256sum verification.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding wget inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

By default, wget strictly validates TLS/SSL certificates against the system CA bundle. Never use the --no-check-certificate option in production scripts, as it disables cryptographic verification and exposes your data transfers to Man-in-the-Middle (MitM) packet interception and spoofing.

Passing credentials on the command line via --user and --password options exposes sensitive passwords in plain text in the system process table (/proc/[pid]/cmdline), viewable by other logged-in users. Instead, store credentials securely in your private ~/.wgetrc configuration file (permissions 600).

GNU/Linux, BSD, and BusyBox Implementation Differences

The full GNU Wget utility is standard on Ubuntu, Debian, RHEL, Rocky Linux, and Arch Linux. However, minimal container images (such as Alpine Linux) and embedded routers provide BusyBox wget. BusyBox wget is a stripped-down implementation lacking recursive mirroring (-m, -r), download resumption (-c), and rate limiting (--limit-rate).

GNU Wget2 is the next-generation rewrite of wget, offering multi-threaded parallel downloads, HTTP/2 support, and improved compression algorithms. While Wget2 provides significant performance gains, standard scripts remain written for GNU Wget 1.x for universal compatibility.

Troubleshooting Common Errors and Diagnostics

ERROR 403: Forbidden or blocked User-Agent

Root Cause: The remote web server or Cloudflare/WAF edge is blocking the default 'Wget/1.x' User-Agent string to prevent scraping.

Resolution: Override the User-Agent header using the -U option to mimic a standard browser.

wget -U "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" https://example.com/file.zip

The certificate's owner does not match hostname (SSL error)

Root Cause: The web server's TLS certificate has expired, is self-signed, or does not match the requested domain name.

Resolution: Update system CA certificates (sudo apt install --reinstall ca-certificates) or investigate domain routing.

sudo update-ca-certificates

Cannot write to 'filename': No space left on device

Root Cause: The target filesystem ran out of available disk space or exhausted available inode allocations during download.

Resolution: Check available disk space with df -h and inodes with df -i, or redirect the download to a different partition with -P.

df -h /tmp
wget -P /mnt/large_storage/ https://example.com/large_file.iso

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
wget is an autonomous non-interactive file downloader that excels at recursive website mirroring and download resumption. curl is a multi-protocol data transfer library (libcurl) designed for fine-grained REST API interactions, sending custom headers, and piping output directly into other programs.
Simply rerun the exact same command with the -c (--continue) option added: wget -c https://example.com/largefile.zip. Wget will inspect the existing local file and fetch only the remaining bytes.
Use the --http-user and --http-password flags (or --ftp-user/--ftp-password for FTP): wget --http-user=admin --http-password=secret https://example.com/protected.zip. For security, store these credentials in ~/.wgetrc instead of the CLI.
Pass -e robots=off on the command line: wget -m -e robots=off https://example.com/docs/. Always ensure you have permission before bypassing a site's crawling policies.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Web Server•

How to Fix 400 Bad Request Error: 10 Easy Ways

Encountering an HTTP error can be frustrating, especially when the cause is unclear. One such error is the "400 Bad Request Error". This issue typically arises due to client-side problems, including incorrect syntax, invalid requests, or la...

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout