1

I have the following test case that I am trying to work with:

countAlpha=10;bob=alpha; echo $(echo $bob | sed 's/[a-z]/\U&/; s/^/\$count/') $countAlpha

Which produces the following:

$countAlpha 10

What I am trying to do is find a way to execute/expand the $countAlpha so that I can use a pipe to generate a variable that can be used in other executions. So the intended goal is to have:

10 10

as the output (the variable is echoed after as a sanity to check to ensure that the bash one liner actually had the correct value, but will not be used in the final result, otherwise this would not need to be asked). Unfortunately these will not always be numbers, use of bash addition for offsets such as $((i +x)) would not be helpful here.

I know that there are many ways to escape in bash (such as " " and ' ' depending on level of escape) but have no concept of how to do the opposite. Thanks in advance.

2
  • 2
    Instead of messing with generating code for the shell to evaluate, use an associative array instead: unix.stackexchange.com/a/463998/170373
    – ilkkachu
    Jan 5, 2022 at 19:06
  • Indeed. An associative array will allow you to write far more robust code Jan 5, 2022 at 19:48

1 Answer 1

1

So after fiddling with it more, I have found the answer and wanted to share it back.

countAlpha=10;bob=alpha; echo $(eval echo $(echo $bob | sed 's/[a-z]/\U&/; s/^/\$count/')) $countAlpha
10

The key part is using the echo $(eval echo $(...)) to allow for the variable to be interpreted, and the additional echo to all for the variable to be printed.

So for clarity, if one wanted to execute using this it would be in form $(eval echo $(...)) and print the value echo $(eval echo $(...)).

While I appreciate the comments about an associative array, in this case I was hoping to do this directly as shown above.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .