Home > Mobile >  How to know if string is empty in zsh?
How to know if string is empty in zsh?

Time:09-02

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

CodePudding user response:

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
  • Related