Home > Software engineering >  Using a string value with the name of an existing variable to get the value of the existing variable
Using a string value with the name of an existing variable to get the value of the existing variable

Time:10-21

I am using a bash script in an azure devops pipeline where a variable is created dynamically from one of the pipeline tasks.

I need to use the variable's value in subsequent scripts, I can formulate the string which is used for the variable name, however cannot get the value of the variable using this string. I hope the below example makes it clear on what I need. Thanks in advance for your help.

PartAPartB="This is my text"
echo "$PartAPartB" #Shows "This is my text" as expected

#HOW DO I GET BELOW TO PRINT "This is my text"
#without using the PartAPartB variable and 
#using VarAB value to become the variable name

VarAB="PartAPartB"
VARNAME="$VarAB" 
echo $("$VARNAME") #INCORRECT

CodePudding user response:

You can use eval to do this

$ PartAPartB="This is my text"
$ VarAB="PartAPartB"
$ eval "echo \${${VarAB}}"
This is my text

CodePudding user response:

You have two choices with bash. Using a nameref with declare -n (which is the preferred approach for Bash >= 4.26) or using variable indirection. In your case, examples of both would be:

#!/bin/bash

VarAB="PartAPartB"

## using a nameref
declare -n VARNAME=VarAB
echo "$VARNAME"           # CORRECT

## using indirection
othervar=VarAB
echo "${!othervar}"       # Also Correct

(note: do not use ALLCAPS variable names, those a generally reserved for environment variables or system variables)

  •  Tags:  
  • bash
  • Related