Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH - Positional Parameters

Tags:

bash

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

like image 901
lrac22 Avatar asked Oct 23 '25 15:10

lrac22


1 Answers

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.

like image 55
ruakh Avatar answered Oct 25 '25 04:10

ruakh