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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks was banging my head to figure this out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.