mathewM
mathewM

Reputation: 139

How to get parameter with variable?

I have problem with getting value of parameter when I have variable with some value. What I mean is:

Example:

./script 12 13 14 15 16

value=5
echo $value #now I see 5
$"$value" #now I want to get 16 but I don't know how to do it?

Upvotes: 0

Views: 671

Answers (4)

William Pursell
William Pursell

Reputation: 212238

bashisms are inherently non-portable. If you rely on ${!...} to evaluate the expression, your script will only run in bash. This may not be an issue, but it is an issue if the author of the script is blissfully unaware of the lack of portability. This sort of thing is trivial to do without relying of bashisms. If you want to evaluate a string, use eval:

eval echo \$$value

Upvotes: 0

chenpp
chenpp

Reputation: 11

try this as well:

value=5              #
echo "$value"        # 5 
echo ${@:$value:1}   # give you 1 arg starting from $value in the arg list     

Upvotes: 1

c00kiemon5ter
c00kiemon5ter

Reputation: 17604

you need to dereference that variable

value=5
echo "$value"      # 5
echo "${!value}"   # will give you $5 or in your example 16

Upvotes: 0

Paul
Paul

Reputation: 141839

Use indirection:

echo "${!value}"

Quotes aren't necessary for the value 16, but should be used in case the variable contains special characters.

Upvotes: 4

Related Questions