Use variable in bash

$ p="1 2 5 8"
$ set -- $p
$ echo $3
5
$ k=3
$ echo \$${k}
$3

I want the "echo \$${k}" to get the output 5 , how to modify ?

echo $(eval echo \$${k})

(although using eval is generally frowned upon as it can introduce security holes)

1 Like

Check this link.

can you explain ?

balajesuri's link gives a better way (and an explanation of why eval can be bad).

You could also use eval echo \$$k with all the known caveats on eval.

Could use put the values into an array and address is that way?

#!/bin/ksh

set -A p 1 2 5 8
k=2
echo "${p[$k]}"

Note that the array counter is 2 to get the output 5.

I don't see an operating system named or a shell, so you might have to adjust this if you want anything other than ksh

I hope that this helps.

Robin
Liverpool/Blackburn
UK