mora
mora

Reputation: 2287

Can I make an alias of variable in bash?

I would like to check existence of a variable in bash like following.

if [ -z "$VARIABLE" ]; then
  echo "VARIABLE does not exist"
else
  echo "VARIABLE exist"
fi

It works fine. But in the next step, I would like to generate a variable name and check whether the variable with the variable name exists or not like following.

function generate_var_name() { echo "aaa" }

VARIABLE_NAME=$(generate_var_name)
if [ -z ${$VARIABLE_NAME:-""} ]; then  # This give error message below.
  echo "VARIABLE does not exist"
else
  echo "VARIABLE exist"
fi

However it did not work. Its error messages was

${"$INCLUD_GUARD_NAME":-""}: bad substitution

Again, what I would like to do is (1) generate a variable name, nameA, and store it to another variable, VarB. (2) using the variable varB, check whether variable with nameA exists or not.

Someone who has solution or suggestion, please tell me it.

Thank you very much.

Upvotes: 0

Views: 58

Answers (2)

merlin2011
merlin2011

Reputation: 75579

It looks like you want an indirect expansion of a variable. Also, it appears that the conditions are reversed in your conditional.

export aaa=foobar
VARIABLE_NAME=aaa

if [ -n "${!VARIABLE_NAME}" ]; then
  echo "VARIABLE exist"
else
  echo "VARIABLE does not exist"
fi

Update: As @chepner correctly pointed out, the test above does not actually check for whether a variable is defined, but rather whether the variable evaluates to an empty string. This check works only if the goal is to consider an undefined variable and a variable defined to equal to the empty string equivalent. Please see @chepner's answer for a correct existence check of a variable.

Upvotes: 3

chepner
chepner

Reputation: 532053

bash already has a test for the existence of a variable:

foo=3   # non-empty value
bar=    # empty value
# baz is not set
for v in foo bar baz; do
    if [[ -v $v ]]; then
        echo "$v is set; its value is ${!v}"
    else
        echo "$v is not set"
    fi
done

Upvotes: 1

Related Questions