0

I'm really struggling with getting some dynamically assigned variables working, even though I've been through the rather wonderfully informative SO article that I've been staring at for a couple of hours now ... I just can't seem to get anything working. I'm using Bash 4.4.20 on Ubuntu 18.04.5.

I have a function that sets up some variables, much like:

declare -g AthreadCount
AthreadCount=$(ps -ef | grep svcA) # 2

declare -g BthreadCount
BthreadCount=$(ps -ef | grep svcB) # 4

declare -g CthreadCount
CthreadCount=$(ps -ef | grep svcC) # 1

In another function, I have the array set up of those services:

declare -a -g services=(A B C)

(to be fair I'm parsing a jq result for the declaration of the array, but it is working and globally available in other functions therefore I'm comfortable it's working as expected)

In another function, I want to evaluate each variables' value and I can't get - what I understand to be called "pointer" assignments - working. I believe my code should look like this:

for sts in "${services[@]}"; do
  echo ${sts}
  svc="${sts}threadCount"
  echo ${!svc}
done

And I would expect:

A
2
B
4
C
1

but I end up getting

A

B

C

Obviously it's not working and I've gone through what I believe to be everything I can do in order to get it working.

Thoughts / comments?!

bnoeafk
  • 489
  • 4
  • 16
  • 2
    I'd recommend switching to an associative array (see [BashFAQ #6](http://mywiki.wooledge.org/BashFAQ/006#Associative_Arrays)) if possible. If you do need to debug what you have, put `set -x` before it, so you can see what's actually happening as it runs. Also, `echo $var` [can be highly misleading](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else); you should at least double-quote the variable reference, but often `declare -p var` is even more informative. – Gordon Davisson Oct 26 '21 at 02:17
  • In my humble opinion you just forgot to call your first function and `AthreadCount`, `BthreadCount`, `CthreadCount` are undefined. – Renaud Pacalet Oct 26 '21 at 06:11
  • refactored the code to use mapfile with arrays and it works like a charm and fixed another issue I was having too. Thanks @Gordon – bnoeafk Oct 26 '21 at 21:39

0 Answers0