How do I make the script interpret the variable i
as the positional parameter?
Probably the easiest way to get the positional parameter indexed by a variable in Bash is to apply the array slice notation to $@
. "${@:n:k}"
expands to the positional parameters from n to n+k-1, just like "${array[@]:n:k}"
expands to the array elements from "${array[n]}"
to "${array[n+k-1]}"
. n and k are evaluated using shell arithmetic, so you can do e.g. "${@:a+b-1:1}"
. Just "${@:i:1}"
gives the one parameter at position i
.
Alternatively, the indirect expansion ${!var}
does deal with the positional parameters too, so e.g. with i=2
, "${!i}"
would give "$2"
.
Well, that's shorter than the above, too. On the other hand, namerefs don't work with the positional parameters, declare -n ref=2
gives an error...
See e.g. Does bash provide support for using pointers?
Another way is to copy the list of positional parameters to a named array, and then index that in the usual manner. args=("$@")
to do the copy and then use "${args[i]}"
. Again, the index here is an arithmetic expansion.
Of course, if you're happy to access the positional parameters in ascending order, as is usual, and don't actually need the reverse order which you show, then just use for x in "$@"; do ...
or for x do ...
as in Kusalanda's answer.
But you could also utilize the same looping construct to invert the list of positional parameters first. E.g. this would print dd cc bb aa
, even in plain sh without namers, indirect references or arrays:
set -- aa bb cc dd
first=1
for x in "$@"; do
# on first iteration, clear the list
[ "$first" = 1 ] && set --
first=
set -- "$x" "$@"
done
echo "$@"