Home > Software design >  How do I combine a Variable with the File Parameter in shell?
How do I combine a Variable with the File Parameter in shell?

Time:05-22

.../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?

CodePudding user response:

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}\"

CodePudding user response:

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

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