Use Wget to Download Files and Handle Broken Links on Ubuntu
This guide explains how to utilize the wget command-line utility on Ubuntu to download files efficiently. It covers basic syntax, configuring retry attempts for unstable connections, setting timeouts to prevent hanging, and resuming interrupted downloads to ensure data integrity when dealing with broken links or network issues.
Install Wget
Wget is pre-installed on most Ubuntu systems. To verify installation or install it if missing, run:
sudo apt update
sudo apt install wgetBasic Download Command
To download a file, use the following command followed by the URL:
wget https://example.com/file.zipHandle Broken Links with Retries
Network instability can cause connections to drop. Use the
--tries option to specify how many times wget should
attempt to reconnect before giving up. Setting this to 0
enables infinite retries.
wget --tries=5 https://example.com/file.zipSet Connection Timeouts
Prevent wget from hanging indefinitely on unresponsive servers by
setting a timeout in seconds. The --timeout flag defines
the maximum time to wait for a connection response.
wget --timeout=10 https://example.com/file.zipResume Interrupted Downloads
If a download fails halfway, use the --continue flag to
resume from where it left off rather than starting over. This is
essential for large files over unstable connections.
wget --continue https://example.com/file.zipCombine Options for Graceful Handling
For the most robust download strategy, combine retries, timeouts, and continue flags. This command attempts to download the file 3 times, waits no longer than 15 seconds for a response, and resumes partial downloads automatically.
wget --tries=3 --timeout=15 --continue https://example.com/file.zipCheck Exit Status in Scripts
When using wget in bash scripts, check the exit status to handle
failures programmatically. An exit code of 0 indicates
success, while any other number indicates an error.
wget --tries=3 --timeout=15 https://example.com/file.zip
if [ $? -eq 0 ]; then
echo "Download successful"
else
echo "Download failed"
fi