4

I'm wondering if this could be possible:

scriptname: testing

#! /bin/bash
i=2

arg=`echo "$"$i`

echo $arg      #value should be the value of $2 and not just '$2' string

echo $2

exit 0

command: testing a b

output

$2

b

Is there a way to make the value of $arg equal to the value of $2 which is "b" instead of just displaying the string "$2" aside from just directly assigning the value of $2 to $arg, arg=$2?

Tried doing this arg=echo ${$i} but I get this error: testing: ${$i}: bad substitution

Thanks in advance

0

1 Answer 1

8

Yes; you can use indirect expansion, which looks like this:

i=2
arg="${!i}"          # equivalent to:    arg="$2"

See the fourth paragraph of §3.5.3 "Shell Parameter Expansion" in the Bash Reference Manual.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.