How to Save wget Downloads to a Specific Directory?

The wget command-line utility by default saves downloaded files directly into the current working directory. However, you can easily change this behavior and direct your downloads to a specific folder using the -P (or --directory-prefix) flag. This article provides a quick guide on how to use this flag, syntax examples for both relative and absolute paths, and tips for automatically creating directories that do not yet exist.

The -P Flag Syntax

To redirect your download, append the -P flag followed by the path to your target directory. The basic command structure looks like this:

wget -P /path/to/directory URL

Examples of Using the Directory Prefix Flag

Depending on where your target folder is located, you can specify either an absolute path or a relative path.

wget -P /home/username/Downloads https://example.com/file.zip
wget -P ./downloads/documents https://example.com/file.zip

Automatic Directory Creation

One of the most convenient features of the -P flag is its ability to create directories on the fly. If the specified target directory does not exist yet, wget will automatically create the entire directory tree before initiating the download. You do not need to run a separate mkdir command beforehand.

Alternative Option: Changing the Filename and Path Simultaneously

If you want to change both the target directory and rename the file at the same time, you should use the uppercase -O (or --output-document) flag instead. While -P only specifies the folder prefix, -O allows you to define the exact path and file destination name:

wget -O /path/to/directory/new_name.zip https://example.com/file.zip