通过变量访问位置参数

accessing a positional parameter through a variable

我正在尝试使用变量访问位置参数。

即如果我将一个变量定义为 1,我想访问第一个位置参数,如果我将它定义为 2,我想访问第二个位置参数。

示例: 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)

这可以做到吗?

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

等等,或者你可以像下面那样做:

#!/bin/sh
var=2
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} ]"

您指出的最佳方法:

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