octosquidopus
octosquidopus

Reputation: 3713

How to get the literal value of a variable's variable?

Here's what I'm asking:

a="achoo"
b="bah"
c="clap"
d="dong"
e="eew"

vowels="$a $e"
consonants="$b $c $d"

Of course, I could just use head or sed to parse from the script itself, but I won't.

Upvotes: 0

Views: 624

Answers (3)

mohit
mohit

Reputation: 6064

Use single quotes, around them:

vowels='$a $e'
consonants='$b $c $d'

Upvotes: 1

viraptor
viraptor

Reputation: 34205

You can't do that in the script itself. There is no literal value of vowels other than achoo eew. The string has been interpolated at the moment you assigned it and it's the only value that exists after that line.

If this is your source, you can use indirection via eval and modify the pattern:

> a=123
> b='$a'
> echo $b
$a
> eval 'echo $b'
$a
> eval "echo $b"
123

But that will cause you a lot of problems in case there are any additional quotes in $b

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 225132

Use single quotes to avoid variable expansion when setting vowels and consonants:

vowels='$a $e'
consonants='$b $c $d'

You're out of luck otherwise; the expansion happened at the time of assignment, so vowels and consonants no longer have any references to $a, $b, $c, $d, or $e anymore after they're assigned.

Upvotes: 3

Related Questions