Muthukumar
Muthukumar

Reputation: 9579

Convert a string into a variable in UNIX

I have the following code

let a=1
let b=a

echo $b

When i echo b, i want it to refer it's value (which is 'a'), and display the value of a( which is '1')

Can this be achieved?

Upvotes: 1

Views: 5274

Answers (3)

glenn jackman
glenn jackman

Reputation: 246774

If your shell is bash, then what you wrote actually sets b to "1" (not "a") because the $ is optional in arithmetic expressions (which you force with the use of let).

Without using let, this is the syntax you're looking for (assuming bash): a=1; b=a; echo $b ${!b} which outputs a 1

Upvotes: 0

andy
andy

Reputation: 7018

First, I would argue you don't really want to do this. But instead of convincing you, here's how to do it:

$ let a=1
$ b=a
$ echo $b
a
$ eval "echo \$$b"
1

note that you can't use "let" for the second assignment since you want to access the right-hand-side as a string later.

Upvotes: 2

MByD
MByD

Reputation: 137312

I think you want let b=$a

Upvotes: 1

Related Questions