Peter R
Peter R

Reputation: 3516

How to do substitution within substituion in Bash

Example:

X=TEST
TEST_VAR=123

eval echo ${${X}_VAR}

This gives the error:

${${X}_VAR}: bad substitution

How can I achieve what I'm looking to do?

Upvotes: 3

Views: 294

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84589

Or avoid eval altogether with a nameref (created with declare -n), e.g.

#!/bin/bash

X=TEST
TEST_VAR=123

declare -n foo=${X}_VAR

echo $foo

Example Use/Output

$ ./myscript
123

Upvotes: 2

Rafael
Rafael

Reputation: 7746

Just escape the dollar sign:

eval echo \$${X}_VAR

Upvotes: 2

Related Questions