PesaThe
PesaThe

Reputation: 7499

Declare -n for positional parameters

In the following code, I am using a reference variable declared with declare -n:

declare -n b="a"
echo "$b"

Is using a reference also possible with positional parameters? Let's say I wanted to do something like this:

for ((i=$#; i>=1;i--)); do
    a="${!i}"
    echo "$a"
done

But "simplified", without the need for parameter expansion:

for ((i=$#; i>=1;i--)); do
    declare -n a=$i
    echo "$a"
done

Upvotes: 0

Views: 222

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295363

Namerefs cannot be used to refer to positional parameters.

If you want to iterate over your arguments out-of-order without using parameter expansion syntax for indirect expansion, consider dumping them into a numerically-indexed array and indexing into that:

args=( "$0" "$@" )
for ((i=$#; i<=1; i--)); do
  echo "${args[$i]}"
done

Upvotes: 2

Related Questions