0

Team,

I have multiple variables values to be checked and run for loop but I see no else execution when no such variable is set on bash.

#!/bin/bash
if [[ $TEST_PERF_CLASS="DFC" || $TEST_PERF_CLASS="GFC" && 
${!K8S_Node_Name}="ALLCORDONED" ]]; then
  for node in ${K8S_Node_Name[@]}; do
    kubectl describe $node
  done
else
  printf "Invalid node or No Variables are set in env yet."
fi

expected output:

Invalid node or No Variables are set in env yet.

Actual Output:

prints nothing.. << empty
  • BTW, always quote your expansions: `"${array[@]}"`, not `${array[@]}`; the latter has all the same bugs as (unquoted) `${array[*]}`. Consider making a habit of running your code through http://shellcheck.net/ to catch issues of that type. – Charles Duffy Jun 27 '19 at 20:03
  • Also, generally, I'd suggest more effort to make intended precedence order clear when writing code of this type. – Charles Duffy Jun 27 '19 at 20:06
  • yes above suggestion did help. thanks. –  Jun 27 '19 at 20:14
  • i got the ELSE working but IF is not working when supplied with values to variables. Shall i raise a new question or ask here? –  Jun 27 '19 at 20:49
  • I'd start by logging the actual behavior. `bash -x yourscript` will log the commands with actual values substituted, so you can make sure they are what you think they are. If there's still an obvious issue with such logging in place (and it isn't a duplicate of something already in the knowledge base), go ahead and ask a new question, with a proper [mcve] someone else can copy-and-paste with no changes needed to see the problem themselves. – Charles Duffy Jun 27 '19 at 21:10

1 Answers1

0

Whitespace around the = is critical:

if [[ $TEST_PERF_CLASS = "DFC" || $TEST_PERF_CLASS = "GFC" && ${!K8S_Node_Name} = "ALLCORDONED" ]]; then
  for node in ${K8S_Node_Name[@]}; do
    kubectl describe $node
  done
else
  printf "Invalid node or No Variables are set in env yet."
fi

Otherwise, you are simply testing that 3 non-empty strings are in fact nonempty. Your original command was equivalent to

if [[ -n $TEST_PERF_CLASS="DFC" || -n $TEST_PERF_CLASS="GFC" && -n ${!K8S_Node_Name}="ALLCORDONED" ]]; then
chepner
  • 497,756
  • 71
  • 530
  • 681