Check if unknown variable is set in bash

I want to check if a variable is set or not. I saw a harsh message about these topics, but not for the next use case. In my case, I have an infinite number of variables (BASE1 ... BASEn), and I want to check whether BASEX variables have been defined or not.

BASE="BAS0"
BASE1="BAS1"
BASE2="BAS2"
BASE3=""

var="";
cpt=0;
while true
do
    if [ $cpt -eq 0 ];
    then
            if ! ${BASE+false};
            then
                    echo "BASE:${BASE}is set";  ### -->  Ok it works
            else
                    echo "NOT set";
                    break;
            fi
    else
            if [ -z BASE${cpt} ];  ### ---> don t work
            then
                    if [ "BASE${cpt}" = "" ];
                    then
                            echo "BASE:${BASE}is set"; 
                    else
                            echo "BASE:${BASE}is empty ! ==> exit";
                            exit 0;
                    fi
            else
                    val="BASE${cpt}"
                    echo "$val NOT set";  ### -->  Always here !
                    break;
            fi
    fi
    cpt=`expr $cpt + 1`;
done

I tried harsh ways, but without success:

if [ -z BASE${cpt} ]; ### ---> don t work
if ! ${BASE${cpt}+x}; ### ---> don t work
...

How can i do this?

Thanks in advance.

+4
source share
2 answers

Since you are dynamically creating a variable name, you probably need an indirect reference:

var="BASE$cpt"
if [ -z "${!var}" ]
+3
source

It looks like you should use an array.

base=(BAS0 BAS1 BAS2 "")
for ((i=0; i<=4; ++i)); do
    echo "$i: ${base[$i]-false}"
done

, , , , , .

+3

All Articles