0
function export_if_empty {
    [[ -z "$1" ]] && declare -gx "${1}"="$2"
}
export_if_empty 'XDG_CONFIG_HOME'   "$HOME/.config"
export_if_empty 'XDG_DATA_HOME'     "$HOME/.local/share"
export_if_empty 'XDG_CACHE_HOME'    "$HOME/.cache"
export_if_empty 'XDG_DATA_DIRS'     '/usr/share:/usr/local/share'
export_if_empty 'XDG_CONFIG_DIRS'   '/etc/xdg'
unset -f export_if_empty

This does not work. even if the XDG_CONFIG_HOME is empty, -z flag fails to correctly identify it

Please check this image to know what I mean

1
  • You never pass an empty $1 to your script. Call your script with export_if_empty '' JustATest, and you will see that the -z test is true. Commented Sep 2, 2022 at 7:15

1 Answer 1

4

You are testing the string XDG_CONFIG_HOME itself, not the value of the variable named XDG_CONFIG_HOME. You need indirect parameter expansion

[[ -z "${(P)1}" ]] && declare -gx "$1=$2"

The (P) flag specifies the value of the parameter be use as the name of another variable to expand, for example:

$ foo=bar bar=3
$ echo $foo
bar
$ echo ${(P)foo}
3
1
  • Thanks was banging my head to figure this out. Commented Sep 2, 2022 at 0:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.