4

I want to check if a variable is set or not. I saw severeal post about this topics but not for the following use case. In my case, I have an infinite number of variable ( BASE1 ... BASEn) and I want to check if BASEX variables was 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 severeal ways but whithout success :

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

How can I do ?

Thanks in advance.

2 Answers 2

3

Since you are constructing the name of the variable dynamically, you probably need an indirect reference:

var="BASE$cpt"
if [ -z "${!var}" ]
Sign up to request clarification or add additional context in comments.

Comments

3

Sounds like you should use an array instead.

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

Incidentally, you should probably use lowercase for your variable names, in keeping with the convention that uppercase is reserved for the shell's internal use.

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.