David Refaeli David Refaeli - 1 year ago 57
Bash Question

accessing a positional parameter through a variable

I'm trying to access a positional parameter using a variable.

i.e. if I define a variable as 1, I want to access the 1st positional parameter, if I define it as 2 I want to access the 2nd positional parameter.

bash script.bash arg1 arg2 arg3

echo $var // will only echo no. 2
??? // insert your command to echo the 2nd positional parameter (arg2)

can this be done?

Answer Source


[[ "$var" -eq "1" ]] && echo "$1" #for positional parameter 1

and so on or you could do it like below :

eval echo "\$${var}" # This will display the second positional parameter an so on


how do I use this if I actually need to access outside of echo. for example "if [ -f \$${var} ]"

The method you've pointed out it the best way:

eval temp="\$${var}"
if [ -f "$temp" ] # Do double quote
#do something
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download