0

I have multiple variables in an array, I want to loop through each of those variables and find if they are empty.

Code:

declare -a CONFIG_PARAM=( $Var_MODE $Var_Path $Var_Stage $Var_line $Var_CVG $Var_Operator )
for PARAMS in "${CONFIG_PARAM[@]}"; do 
   if [ ! $PARAMS ]; then 
      echo -e "$PARAMS is empty"
   fi
done;

But it doesnt seem to catch the empty variables. Can someone point out what is wrong or provide any suggestion/solution? Thanks in advance for any help.

4
  • 2
    Quotes. "$Var_MODE" "$Var_PATH" etc. And [ ! "$PARAMS" ] Commented Sep 29, 2017 at 16:07
  • But that's only if you needed the values. If you need the names, then you need to use an indirect expansion. Commented Sep 29, 2017 at 16:07
  • Thanks I just tried the and got the values but I needed the variable names to be printed! Commented Sep 29, 2017 at 16:10
  • Hmm. Arguably this is a duplicate of can I do a for loop over variables in the bash shell Commented Sep 29, 2017 at 16:12

2 Answers 2

3
declare -a config_params=( Var_MODE Var_Path Var_Stage Var_line Var_CVG Var_Operator )
for param in "${config_params[@]}"; do 
   if ! [ -n "${!param}" ]; then 
      echo "$param is empty"
   fi
done

Note:

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much, this is very helpful. But I have tried the code above, it still prints the values of variables instead of the varible names.
@GopinathS, ...uh... no, it doesn't. See this code actually running at ideone.com/4iUpnd
My bad, I didn't remove '$' for variables in the array, sorry about that. Now I understood the indirect-reference concept from your note. Thanks a lot, appreciate your help.
1

This is a case where (IMO) the loop makes your code less readable. There is something to be said for a nice vertical list of calls, one line per variable.

check_empty () {
    [ -z "${!1}" ] && printf '%s is empty\n' "$1"
}

and make a separate call for each variable.

check_empty Var_MODE
check_empty Var_Path
check_empty Var_Stage
check_empty Var_line
check_empty Var_CVG
check_empty Var_Operator

Actually, you don't even need a separate function. The parameter expansion operator :? will display an error message, with the name of the variable, if it is empty.

: ${Var_MODE?empty} || :
: ${Var_Path?empty} || :
: ${Var_Stage?empty} || :
: ${Var_line?empty} || :
: ${Var_CVG?empty} || :
: ${Var_Operator?empty} || :

The trailing || : prevents the script from exiting when the variable is empty.

Comments

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.