How to Force Wget to Overwrite an Existing File?
By default, GNU wget avoids overwriting existing files
by automatically appending a numeric suffix (like .1,
.2) to the newly downloaded file name. However, when
automating scripts or updating local resources, you often need to force
wget to overwrite the original file instead of creating
duplicates. This article covers the specific command-line flags and
configurations required to achieve this behavior, ranging from simple
output redirection to clobbering settings.
The Standard Solution: Output File Redirection
The most reliable way to force wget to overwrite an
existing file is by using the -O (uppercase letter O)
option. This flag tells wget to concatenate all downloaded
data and write it precisely to the specified filename, ignoring the
default suffix-incrementing behavior.
wget -O filename.ext URLFor example, if you want to download a file named
setup.sh and overwrite any existing copy in your current
directory, you would run:
wget -O setup.sh https://example.com/setup.shThe Clashing Option: Understanding Clobbering
Another method involves managing wget’s built-in
“clobbering” feature. By default, wget is set to
---clobber, which ironically allows it to create the
.1 suffixes to protect your files. To prevent this and
force an overwrite, you can use the combination of turn-on and turn-off
flags depending on your specific use case.
- Using
--backups=0: If you use the timestamping feature (-N),wgetnormally creates backup files. You can force it to overwrite the old file without creating backups by setting the backup count to zero.
wget -N --backups=0 URLOverwriting via Shell Redirection
If you prefer to let the shell handle the file creation and
overwriting rather than wget’s internal mechanisms, you can
instruct wget to send the downloaded content directly to
standard output (-O -) and pipe it into a file.
wget -O - URL > filename.extUsing the > operator inherently truncates and
overwrites the target file if it already exists, providing a foolproof
workaround in most Linux environments.