David Refaeli David Refaeli - 4 months ago 8
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.

example:
bash script.bash arg1 arg2 arg3

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


can this be done?

Answer

Do

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

and so on or you could do it like below :

#!/bin/sh
var=2
eval echo "\$${var}" # This will display the second positional parameter an so on

Edit

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:

var=2 
eval temp="\$${var}"
if [ -f "$temp" ] # Do double quote
then
#do something
fi
Comments