1

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?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Maverick Meerkat
  • 5,737
  • 3
  • 47
  • 66
  • Yes! thanks. But just to make it easier for other readers - you access it like this: ${!var}, i.e. ehco ${!var} will echo arg2 – Maverick Meerkat Aug 01 '16 at 06:59
  • But that solution will make the script less portable, see the comments that follow my answer. – sjsam Aug 01 '16 at 07:09

1 Answers1

2

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
sjsam
  • 21,411
  • 5
  • 55
  • 102