Skip to content
Advertisement

Indirect expansion returns variable name instead of value

I am trying to set up some variables using indirect expansion. According to the documentation I’ve read, the set up should be simple:

var1=qa
qa_num=12345
varname="${var1}_ci"

echo ${!varname}

I should be getting “12345”. Instead, the output is “varname”. If I remove the exclamation point, I end up with “qa_ci”, not “12345”

This should be a relatively simple solution, so I’m not sure what I’m missing, if anything.

Advertisement

Answer

Your code defines qa_num, but the varname assignment references qa_ci. As a result, your echo was expanding nonexistent qa_ci, giving empty results. Changing the varname assignment fixes the problem on my system.

Example: foo.sh:

#!/bin/bash
var1=qa
qa_num=12345
varname="${var1}_num"     # <=== not _ci

echo "${!varname}"        # I also added "" here as a general good practice

Output:

$ bash foo.sh
12345
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement