0

Not sure how to explain this but I am trying to create a variable on the fly of an existing variable. But not sure how to explain it. I have tried many different ways bit its now about to blow my mind.

# existing variable
count_completed=10
count_failed=2

showCount() {
  if [ "$1" == "completed" ]; then
   echo ${1^^} count is $count_${1,,}
  fi
}

showCount "failed"

I've tried to create another variable and escaped the dollars and then tried echo that variable, but it didn't work

newvar=\$count_\${1,,}
echo ${1^^} $newvar

Im not sure what I'm doing wrong... :) its a very unique issue; Can't find any examples of what I'm looking for or what I should be asking for...

Khorem
  • 61
  • 5
  • 1
    Maybe the verb "interpolate"? – Jeff Holt Jul 23 '21 at 02:03
  • 1
    Generally trying to do something like that is a big sign you should be using an associative array instead. – Shawn Jul 23 '21 at 02:03
  • 1
    See [BashFAQ #6: "How can I use variable variables (indirect variables, pointers, references) or associative arrays?"](http://mywiki.wooledge.org/BashFAQ/006) and the many questions here about indirect expansion and/or nameref variables, like ["How to get a variable value if variable name is stored as string?"](https://stackoverflow.com/questions/1921279/how-to-get-a-variable-value-if-variable-name-is-stored-as-string). Hint: associative arrays are almost always better. – Gordon Davisson Jul 23 '21 at 02:16
  • if I do the following: newvar=\$count_${1,,} echo $newvar the variable displays right variable but the error says invalid number – Khorem Jul 23 '21 at 02:26
  • never mind, eval newvar .... that worked! – Khorem Jul 23 '21 at 02:29
  • 5
    @Khorem `eval` should be avoided whenever possible. If you don't understand exactly how shell parsing works, it's way to easy to get bizarre and sometimes dangerous bugs with it. – Gordon Davisson Jul 23 '21 at 02:49
  • 2
    @Khorem : Why aren't you using an associative array instead? It's easier to understand and IMO safer too. – user1934428 Jul 23 '21 at 06:43

0 Answers0