How can a Bash script locate the user’s Downloads folder in any locale?

0
8
Asked By VelvetPanda47 On

I'm new to Bash and need an installation script for Linux/Ubuntu. The script should locate the current user's Downloads directory, whether it is named "Downloads" or the French "Téléchargements," and store the full path in a variable. The username is not known ahead of time. I'd then like to use that variable to change into the directory and work with downloaded files, such as installing a package. What is the most reliable way to do this?

3 Answers

Answered By CedarFox82 On

Use the standard XDG user-directory command instead of checking translated folder names manually. It reads the user’s locale configuration and returns the configured Downloads directory: `download_dir="$(xdg-user-dir DOWNLOAD)"`. You can then use it safely like this:

`cd -- "$download_dir" || exit 1`

If the directory does not exist or is not configured, the command may return the user’s home directory, so it’s a good idea to verify the result before downloading or installing anything.

VelvetPanda47 -

That makes sense. I can use the returned path as `$download_dir` for the rest of the installation script, and the `$HOME` advice also avoids having to determine the username myself.

Answered By MossyOrbit19 On

If you specifically want to check the two possible directory names, use `$HOME` rather than `$USER`. `$HOME` already contains the current user’s full home directory and may not always be `/home/$USER`. Quote it in case the path contains spaces:

`if [ -d "$HOME/Downloads" ]; then`
` download_dir="$HOME/Downloads"`
`elif [ -d "$HOME/Téléchargements" ]; then`
` download_dir="$HOME/Téléchargements"`
`else`
` printf 'Downloads directory not foundn' >&2`
` exit 1`
`fi`

After that, use `"$download_dir"` whenever you refer to the folder.

Answered By QuietMaple6 On

Avoid relying on `$USER` for the username because it is an environment variable and can be changed. If you truly need the login name, `id -un` is more reliable. However, for the current user’s files, `$HOME` is simpler and safer than reconstructing a path from a username.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.