0

Here is the scenario: suppose I set positional variables:

set 1 2 3 4
eval "args_$1=something"

how do I read args_1,args_2,args_3... variables I tried

echo $args_$1

and this also not working

eval "\$$(echo arg_$1)"

How do I get value of $arg_1, to display on terminal or pass to a function, etc.

Superdav
  • 29
  • 6
  • 1
    http://mywiki.wooledge.org/BashFAQ/006 – Etan Reisner Apr 14 '15 at 00:41
  • Using eval is not recommended but, you can try: set 1 2 3 4; eval arg_$1=koba; eval echo $\`echo arg_$1\` – AKS Apr 14 '15 at 00:44
  • 1
    The answer I most strongly endorse from the linked question, by the way, is http://stackoverflow.com/a/16973754/14122 -- which, in the case given here, would mean something like `printf -v "$args_$1" %s value` – Charles Duffy Apr 14 '15 at 01:38
  • ...but really, read BashFAQ #6 for a more complete answer / set of approaches than what's available here on StackOverflow. – Charles Duffy Apr 14 '15 at 01:45

2 Answers2

2

Without eval:

$ set 1 2 3 4
$ var="args_$1"
$ declare "$var=foo"
$ echo "$var"
args_1
$ echo "${!var}"
foo

This uses an indirect variable.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
1
$ set 1 2 3 4; eval arg_$1=koba; eval echo $`echo arg_$1`
koba

PS: Using eval is not recommended.

AKS
  • 16,482
  • 43
  • 166
  • 258