0

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
  • 1
    I suggest `echo "${!VARNAME}"`. – Cyrus Oct 21 '22 at 00:26
  • See: [Accessing indirect shell variables in Bash](https://stackoverflow.com/q/43991626/3776858) – Cyrus Oct 21 '22 at 00:28
  • 1
    Does this answer your question? [Accessing indirect shell variables in Bash](https://stackoverflow.com/questions/43991626/accessing-indirect-shell-variables-in-bash) – joanis Oct 21 '22 at 01:19

2 Answers2

0

You can use eval to do this

$ PartAPartB="This is my text"
$ VarAB="PartAPartB"
$ eval "echo \${${VarAB}}"
This is my text
WeDBA
  • 343
  • 4
  • 7
0

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)

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85