Home > Software design >  Variable set with `elif [[ -n ${var=$(mycommand ...args...)} ]]` unexpectedly empty
Variable set with `elif [[ -n ${var=$(mycommand ...args...)} ]]` unexpectedly empty

Time:01-24

I'm not sure if this is a good way to define a variable inside an elif statement.

I want to set VALUE with the value of CUSTOM_KEY if it contains something else get the value from the configmap.

It seems that sometimes it can take few seconds to run the command in the second elif statement and I'm unsure if it can affect the result of the command.

if [[ -n "${CUSTOM_KEY}" ]]; then

    VALUE="${CUSTOM_KEY}"

    echo "VALUE: ${VALUE} set from CUSTOM_KEY"

elif [[ -n "${VALUE="$(kubectl get configmap configmapvalue -n "${N}" -o jsonpath="{.data.VALUE}")"}" ]]; then

     echo "VALUE: ${VALUE} set from configmap configmapvalue"

else

     echo "Please, define a CUSTOM_VALUE"

fi

echo "${VALUE}"

CodePudding user response:

The immediate problem is that ${var=value} only assigns to var when the variable is previously unset.

We don't know that it's unset, because [ -n "$var" ] tests only if it's empty. A variable can be set to an empty value, in which case ${var=default} won't change it, but ${var:=default} will.


You don't need to use ${var=default} or ${var:=default}, though, because if the elif clause is executed at all, you know that you need to update the value from kubectl. Thus:

elif VALUE=$(kubectl get configmap configmapvalue -n "$N" -o jsonpath='{.data.VALUE}') && [[ $VALUE ]]; then
  • Related