1

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.

cxw
  • 16,685
  • 2
  • 45
  • 81
SVill
  • 331
  • 5
  • 22
  • 55

1 Answers1

1

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
cxw
  • 16,685
  • 2
  • 45
  • 81
  • This worked, though I should mention that the typo only existed on this question, not the actual code. On that note, I was trying these lines in the linux console and they did not work. Only when I created an actual script with it. Why does that make a difference? – SVill Jun 25 '19 at 17:58
  • @SVill I'm not sure. On my Cygwin bash, the four lines of `foo.sh`, run one at a time in the console, result in `12345`, as they should. However, more complicated scripts (e.g., that rely on `shopt` settings) sometimes behave differently in the shell. I'd suggest asking a new question with a minimal, testable example of the difference in behaviour. Good luck! – cxw Jun 25 '19 at 18:08