Bash – How to utilize XDG directories and paths in Bash

bashdirectory-structurefreedesktop

I wonder how to access not only the variables defined in ~/.config/user-dirs.dirs with xdg-user-dir, e.g. "$(xdg-user-dir VIDEOS)", but also the following standard variables:

  1. XDG_CACHE_HOME:-$HOME/.cache
  2. XDG_CONFIG_HOME:-$HOME/.config
  3. XDG_DATA_HOME:-$HOME/.local/share
  4. XDG_RUNTIME_DIR:-"/run/user/$USER"
  5. XDG_CONFIG_DIRS:-/etc/xdg
  6. XDG_DATA_DIRS:-/usr/local/share:/usr/share

For that purpose I do the following in my ~/.bash_login file:

# Define standard directories.
declare -gx XDG_CACHE_HOME=~/.cache
declare -gx XDG_CONFIG_HOME=~/.config
declare -gx XDG_DATA_HOME=~/.local/share
declare -gx XDG_RUNTIME_DIR="/run/user/$USER"
declare -gx XDG_CONFIG_DIRS="$(IFS=: path /etc/xdg)"
declare -gx XDG_DATA_DIRS="$(IFS=: path /usr/local/share:/usr/share)"
# Source supplementary directories to export or overwrite existing standard ones.
declare a="$XDG_CONFIG_HOME/user-dirs.dirs"
if [[ -e $a ]]; then
  source "$a"
  declare b=""
  for b in ${!XDG_*}; do
    if [[ $b =~ ^XDG_[_[:alnum:]]+_DIR$ ]]; then
      declare -gx "$b"
    fi
  done
fi

Is there a mechanism to access the above directory and path variables other than the user directory variables defined by the "XDG" directory structure specification?

Best Answer

Those environment variables are all optional. If they are not set then your script must substitute the default values given in the specification itself.

someprog --cachedir "${XDG_CACHE_HOME:-$HOME/.cache}"
Related Question