1

I was writing a script where I came across a situation.

Audio_Repo = "/src/audio_123";
Audio_ImgTag = "aud021882";
Audio_Enable = 1;
.....
Video_Repo = "/src/vid_823";
Video_ImgTag = "video9282";
Video_Enable = 0;
....


#Say proj_var ="Audio"
#it could be either Audio or Video  based on some conditional check
....
proj_var = "Audio"
....
PROJECT_REPO= ${!{$proj_var"_Repo"}}
#PROJECT_REPO should hold the value "src/audio_123" 

But the above representation throws bad substitution error I know that I could use a temporary variable as follows

temp= $proj_var"_Repo";
PROJECT_REPO = ${!temp};

But I have many properties and I do not want to use temporary variables for each of them. Instead I want single line substitutions.

amv
  • 81
  • 8

2 Answers2

0

One way to do it is to use eval:

#! /bin/bash -p

Audio_Repo="/src/audio_123"
Audio_ImgTag=aud021882
Audio_Enable=1
# ...
Video_Repo=/src/vid_823
Video_ImgTag=video9282
Video_Enable=0
# ....


# Say proj_var="Audio"
# it could be either Audio or Video  based on some conditional check
# ....
proj_var="Audio"
# ....

eval "Project_Repo=\${${proj_var}_Repo}"

# Project_Repo should hold the value "src/audio_123" 
printf '%s\n' "$Project_Repo"

Another option is to use a helper function:

# ...

# Set the value of the variable whose name is in the first parameter ($1)
# to the value of the variable whose name is in the second parameter ($2).
function setn { printf -v "$1" '%s' "${!2}" ; }

# ...

setn Project_Repo "${proj_var}_Repo"

Using the setn (a poor name, choose a better one) function avoids both a temporary variable and eval.

pjh
  • 6,388
  • 2
  • 16
  • 17
0

Uses arrays, not variable names you need to manipulate.

Repo=0
ImgTag=1
Enable=2

Audio=(/src/audio_123 aud021882 1)
Video=(/src/vid_823 video9282 0)

proj_repo=Audio[$Repo]
project_var=${!proj_repo}
chepner
  • 497,756
  • 71
  • 530
  • 681