'How do I combine a Variable with the File Parameter in shell?

.../sh

when I type "$3" I would get the third parameter, but I want to use a variable instead of the static 3. How can I do that?



Solution 1:[1]

With bash, you use variable indirection (documented in 3.5.3 Shell Parameter Expansion)

set -- one two three
n=3
echo "${!n}"   # => three

# or, use $n as an index into the positional parameters "array"
echo "${@:n:1}"    # => three

For sh, I think eval is required: this is a copy-paste from a dash shell

$ set -- one two three
$ echo $3
three
$ n=3
$ echo $n
3
$ echo ${!n}
dash: 5: Bad substitution
$ eval echo \$$n
three

Although, to be properly quote, I think that looks like

eval echo \"\${$n}\"

Solution 2:[2]

You can shift the number minus one, and get the first param then.

param=3
shift $((param - 1))
echo "$1"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 KamilCuk